xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86ISelLowering.cpp (revision d411c1d696ef35d60f8c3564e5eef7aeafa2fece)
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that X86 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86ISelLowering.h"
15 #include "MCTargetDesc/X86ShuffleDecode.h"
16 #include "X86.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/BlockFrequencyInfo.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/ObjCARCUtil.h"
32 #include "llvm/Analysis/ProfileSummaryInfo.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/IntrinsicLowering.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineJumpTableInfo.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/WinEHFuncInfo.h"
44 #include "llvm/IR/CallingConv.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/DiagnosticInfo.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalAlias.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/IRBuilder.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/PatternMatch.h"
55 #include "llvm/MC/MCAsmInfo.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/MC/MCExpr.h"
58 #include "llvm/MC/MCSymbol.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Target/TargetOptions.h"
65 #include <algorithm>
66 #include <bitset>
67 #include <cctype>
68 #include <numeric>
69 using namespace llvm;
70 
71 #define DEBUG_TYPE "x86-isel"
72 
73 STATISTIC(NumTailCalls, "Number of tail calls");
74 
75 static cl::opt<int> ExperimentalPrefInnermostLoopAlignment(
76     "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
77     cl::desc(
78         "Sets the preferable loop alignment for experiments (as log2 bytes) "
79         "for innermost loops only. If specified, this option overrides "
80         "alignment set by x86-experimental-pref-loop-alignment."),
81     cl::Hidden);
82 
83 static cl::opt<bool> MulConstantOptimization(
84     "mul-constant-optimization", cl::init(true),
85     cl::desc("Replace 'mul x, Const' with more effective instructions like "
86              "SHIFT, LEA, etc."),
87     cl::Hidden);
88 
89 static cl::opt<bool> ExperimentalUnorderedISEL(
90     "x86-experimental-unordered-atomic-isel", cl::init(false),
91     cl::desc("Use LoadSDNode and StoreSDNode instead of "
92              "AtomicSDNode for unordered atomic loads and "
93              "stores respectively."),
94     cl::Hidden);
95 
96 /// Call this when the user attempts to do something unsupported, like
97 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
98 /// report_fatal_error, so calling code should attempt to recover without
99 /// crashing.
100 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
101                              const char *Msg) {
102   MachineFunction &MF = DAG.getMachineFunction();
103   DAG.getContext()->diagnose(
104       DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
105 }
106 
107 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
108                                      const X86Subtarget &STI)
109     : TargetLowering(TM), Subtarget(STI) {
110   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
111   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
112 
113   // Set up the TargetLowering object.
114 
115   // X86 is weird. It always uses i8 for shift amounts and setcc results.
116   setBooleanContents(ZeroOrOneBooleanContent);
117   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
118   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
119 
120   // For 64-bit, since we have so many registers, use the ILP scheduler.
121   // For 32-bit, use the register pressure specific scheduling.
122   // For Atom, always use ILP scheduling.
123   if (Subtarget.isAtom())
124     setSchedulingPreference(Sched::ILP);
125   else if (Subtarget.is64Bit())
126     setSchedulingPreference(Sched::ILP);
127   else
128     setSchedulingPreference(Sched::RegPressure);
129   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
130   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
131 
132   // Bypass expensive divides and use cheaper ones.
133   if (TM.getOptLevel() >= CodeGenOpt::Default) {
134     if (Subtarget.hasSlowDivide32())
135       addBypassSlowDiv(32, 8);
136     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
137       addBypassSlowDiv(64, 32);
138   }
139 
140   // Setup Windows compiler runtime calls.
141   if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
142     static const struct {
143       const RTLIB::Libcall Op;
144       const char * const Name;
145       const CallingConv::ID CC;
146     } LibraryCalls[] = {
147       { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
148       { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
149       { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
150       { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
151       { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
152     };
153 
154     for (const auto &LC : LibraryCalls) {
155       setLibcallName(LC.Op, LC.Name);
156       setLibcallCallingConv(LC.Op, LC.CC);
157     }
158   }
159 
160   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
161     // MSVCRT doesn't have powi; fall back to pow
162     setLibcallName(RTLIB::POWI_F32, nullptr);
163     setLibcallName(RTLIB::POWI_F64, nullptr);
164   }
165 
166   // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
167   // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
168   // FIXME: Should we be limiting the atomic size on other configs? Default is
169   // 1024.
170   if (!Subtarget.canUseCMPXCHG8B())
171     setMaxAtomicSizeInBitsSupported(32);
172 
173   // Set up the register classes.
174   addRegisterClass(MVT::i8, &X86::GR8RegClass);
175   addRegisterClass(MVT::i16, &X86::GR16RegClass);
176   addRegisterClass(MVT::i32, &X86::GR32RegClass);
177   if (Subtarget.is64Bit())
178     addRegisterClass(MVT::i64, &X86::GR64RegClass);
179 
180   for (MVT VT : MVT::integer_valuetypes())
181     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
182 
183   // We don't accept any truncstore of integer registers.
184   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
185   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
186   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
187   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
188   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
189   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // SETOEQ and SETUNE require checking two conditions.
194   for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
195     setCondCodeAction(ISD::SETOEQ, VT, Expand);
196     setCondCodeAction(ISD::SETUNE, VT, Expand);
197   }
198 
199   // Integer absolute.
200   if (Subtarget.canUseCMOV()) {
201     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
202     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
203     if (Subtarget.is64Bit())
204       setOperationAction(ISD::ABS          , MVT::i64  , Custom);
205   }
206 
207   // Signed saturation subtraction.
208   setOperationAction(ISD::SSUBSAT          , MVT::i8   , Custom);
209   setOperationAction(ISD::SSUBSAT          , MVT::i16  , Custom);
210   setOperationAction(ISD::SSUBSAT          , MVT::i32  , Custom);
211   if (Subtarget.is64Bit())
212     setOperationAction(ISD::SSUBSAT        , MVT::i64  , Custom);
213 
214   // Funnel shifts.
215   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
216     // For slow shld targets we only lower for code size.
217     LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
218 
219     setOperationAction(ShiftOp             , MVT::i8   , Custom);
220     setOperationAction(ShiftOp             , MVT::i16  , Custom);
221     setOperationAction(ShiftOp             , MVT::i32  , ShiftDoubleAction);
222     if (Subtarget.is64Bit())
223       setOperationAction(ShiftOp           , MVT::i64  , ShiftDoubleAction);
224   }
225 
226   if (!Subtarget.useSoftFloat()) {
227     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
228     // operation.
229     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
230     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
231     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
232     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
233     // We have an algorithm for SSE2, and we turn this into a 64-bit
234     // FILD or VCVTUSI2SS/SD for other targets.
235     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
236     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
237     // We have an algorithm for SSE2->double, and we turn this into a
238     // 64-bit FILD followed by conditional FADD for other targets.
239     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
240     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
241 
242     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
243     // this operation.
244     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
245     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
246     // SSE has no i16 to fp conversion, only i32. We promote in the handler
247     // to allow f80 to use i16 and f64 to use i16 with sse1 only
248     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
249     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
250     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
251     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
252     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
253     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
254     // are Legal, f80 is custom lowered.
255     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
256     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
257 
258     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
259     // this operation.
260     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
261     // FIXME: This doesn't generate invalid exception when it should. PR44019.
262     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
263     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
264     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
265     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
266     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
267     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
268     // are Legal, f80 is custom lowered.
269     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
270     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
271 
272     // Handle FP_TO_UINT by promoting the destination to a larger signed
273     // conversion.
274     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
275     // FIXME: This doesn't generate invalid exception when it should. PR44019.
276     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
277     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
278     // FIXME: This doesn't generate invalid exception when it should. PR44019.
279     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
280     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
281     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
282     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
283     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
284 
285     setOperationAction(ISD::LRINT,             MVT::f32, Custom);
286     setOperationAction(ISD::LRINT,             MVT::f64, Custom);
287     setOperationAction(ISD::LLRINT,            MVT::f32, Custom);
288     setOperationAction(ISD::LLRINT,            MVT::f64, Custom);
289 
290     if (!Subtarget.is64Bit()) {
291       setOperationAction(ISD::LRINT,  MVT::i64, Custom);
292       setOperationAction(ISD::LLRINT, MVT::i64, Custom);
293     }
294   }
295 
296   if (Subtarget.hasSSE2()) {
297     // Custom lowering for saturating float to int conversions.
298     // We handle promotion to larger result types manually.
299     for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
300       setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
301       setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
302     }
303     if (Subtarget.is64Bit()) {
304       setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
305       setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
306     }
307   }
308 
309   // Handle address space casts between mixed sized pointers.
310   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
311   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
312 
313   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
314   if (!Subtarget.hasSSE2()) {
315     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
316     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
317     if (Subtarget.is64Bit()) {
318       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
319       // Without SSE, i64->f64 goes through memory.
320       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
321     }
322   } else if (!Subtarget.is64Bit())
323     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
324 
325   // Scalar integer divide and remainder are lowered to use operations that
326   // produce two results, to match the available instructions. This exposes
327   // the two-result form to trivial CSE, which is able to combine x/y and x%y
328   // into a single instruction.
329   //
330   // Scalar integer multiply-high is also lowered to use two-result
331   // operations, to match the available instructions. However, plain multiply
332   // (low) operations are left as Legal, as there are single-result
333   // instructions for this in x86. Using the two-result multiply instructions
334   // when both high and low results are needed must be arranged by dagcombine.
335   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
336     setOperationAction(ISD::MULHS, VT, Expand);
337     setOperationAction(ISD::MULHU, VT, Expand);
338     setOperationAction(ISD::SDIV, VT, Expand);
339     setOperationAction(ISD::UDIV, VT, Expand);
340     setOperationAction(ISD::SREM, VT, Expand);
341     setOperationAction(ISD::UREM, VT, Expand);
342   }
343 
344   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
345   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
346   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
347                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
348     setOperationAction(ISD::BR_CC,     VT, Expand);
349     setOperationAction(ISD::SELECT_CC, VT, Expand);
350   }
351   if (Subtarget.is64Bit())
352     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
353   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
354   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
355   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
356 
357   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
358   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
359   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
360   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
361 
362   if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
363     setOperationAction(ISD::FLT_ROUNDS_    , MVT::i32  , Custom);
364     setOperationAction(ISD::SET_ROUNDING   , MVT::Other, Custom);
365   }
366 
367   // Promote the i8 variants and force them on up to i32 which has a shorter
368   // encoding.
369   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
370   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
371 
372   if (Subtarget.hasBMI()) {
373     // Promote the i16 zero undef variant and force it on up to i32 when tzcnt
374     // is enabled.
375     setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i16, MVT::i32);
376   } else {
377     setOperationAction(ISD::CTTZ, MVT::i16, Custom);
378     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
379     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Legal);
380     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
381     if (Subtarget.is64Bit()) {
382       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
383       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
384     }
385   }
386 
387   if (Subtarget.hasLZCNT()) {
388     // When promoting the i8 variants, force them to i32 for a shorter
389     // encoding.
390     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
391     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
392   } else {
393     for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
394       if (VT == MVT::i64 && !Subtarget.is64Bit())
395         continue;
396       setOperationAction(ISD::CTLZ           , VT, Custom);
397       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
398     }
399   }
400 
401   for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
402                   ISD::STRICT_FP_TO_FP16}) {
403     // Special handling for half-precision floating point conversions.
404     // If we don't have F16C support, then lower half float conversions
405     // into library calls.
406     setOperationAction(
407         Op, MVT::f32,
408         (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
409     // There's never any support for operations beyond MVT::f32.
410     setOperationAction(Op, MVT::f64, Expand);
411     setOperationAction(Op, MVT::f80, Expand);
412     setOperationAction(Op, MVT::f128, Expand);
413   }
414 
415   for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
416     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
417     setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
418     setTruncStoreAction(VT, MVT::f16, Expand);
419     setTruncStoreAction(VT, MVT::bf16, Expand);
420 
421     setOperationAction(ISD::BF16_TO_FP, VT, Expand);
422     setOperationAction(ISD::FP_TO_BF16, VT, Custom);
423   }
424 
425   setOperationAction(ISD::PARITY, MVT::i8, Custom);
426   setOperationAction(ISD::PARITY, MVT::i16, Custom);
427   setOperationAction(ISD::PARITY, MVT::i32, Custom);
428   if (Subtarget.is64Bit())
429     setOperationAction(ISD::PARITY, MVT::i64, Custom);
430   if (Subtarget.hasPOPCNT()) {
431     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
432     // popcntw is longer to encode than popcntl and also has a false dependency
433     // on the dest that popcntl hasn't had since Cannon Lake.
434     setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
435   } else {
436     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
437     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
438     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
439     if (Subtarget.is64Bit())
440       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
441     else
442       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
443   }
444 
445   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
446 
447   if (!Subtarget.hasMOVBE())
448     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
449 
450   // X86 wants to expand cmov itself.
451   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
452     setOperationAction(ISD::SELECT, VT, Custom);
453     setOperationAction(ISD::SETCC, VT, Custom);
454     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
455     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
456   }
457   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
458     if (VT == MVT::i64 && !Subtarget.is64Bit())
459       continue;
460     setOperationAction(ISD::SELECT, VT, Custom);
461     setOperationAction(ISD::SETCC,  VT, Custom);
462   }
463 
464   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
465   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
466   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
467 
468   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
469   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
470   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
471   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
472   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
473   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
474   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
475     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
476 
477   // Darwin ABI issue.
478   for (auto VT : { MVT::i32, MVT::i64 }) {
479     if (VT == MVT::i64 && !Subtarget.is64Bit())
480       continue;
481     setOperationAction(ISD::ConstantPool    , VT, Custom);
482     setOperationAction(ISD::JumpTable       , VT, Custom);
483     setOperationAction(ISD::GlobalAddress   , VT, Custom);
484     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
485     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
486     setOperationAction(ISD::BlockAddress    , VT, Custom);
487   }
488 
489   // 64-bit shl, sra, srl (iff 32-bit x86)
490   for (auto VT : { MVT::i32, MVT::i64 }) {
491     if (VT == MVT::i64 && !Subtarget.is64Bit())
492       continue;
493     setOperationAction(ISD::SHL_PARTS, VT, Custom);
494     setOperationAction(ISD::SRA_PARTS, VT, Custom);
495     setOperationAction(ISD::SRL_PARTS, VT, Custom);
496   }
497 
498   if (Subtarget.hasSSEPrefetch() || Subtarget.hasThreeDNow())
499     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
500 
501   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
502 
503   // Expand certain atomics
504   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
505     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
511     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
512   }
513 
514   if (!Subtarget.is64Bit())
515     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
516 
517   if (Subtarget.canUseCMPXCHG16B())
518     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
519 
520   // FIXME - use subtarget debug flags
521   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
522       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
523       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
524     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
525   }
526 
527   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
528   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
529 
530   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
531   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
532 
533   setOperationAction(ISD::TRAP, MVT::Other, Legal);
534   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
535   if (Subtarget.isTargetPS())
536     setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
537   else
538     setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
539 
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   bool Is64Bit = Subtarget.is64Bit();
544   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
545   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
546 
547   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
548   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
549 
550   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
551 
552   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
553   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
554   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
555 
556   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
557 
558   auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
559     setOperationAction(ISD::FABS, VT, Action);
560     setOperationAction(ISD::FNEG, VT, Action);
561     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
562     setOperationAction(ISD::FREM, VT, Action);
563     setOperationAction(ISD::FMA, VT, Action);
564     setOperationAction(ISD::FMINNUM, VT, Action);
565     setOperationAction(ISD::FMAXNUM, VT, Action);
566     setOperationAction(ISD::FMINIMUM, VT, Action);
567     setOperationAction(ISD::FMAXIMUM, VT, Action);
568     setOperationAction(ISD::FSIN, VT, Action);
569     setOperationAction(ISD::FCOS, VT, Action);
570     setOperationAction(ISD::FSINCOS, VT, Action);
571     setOperationAction(ISD::FSQRT, VT, Action);
572     setOperationAction(ISD::FPOW, VT, Action);
573     setOperationAction(ISD::FLOG, VT, Action);
574     setOperationAction(ISD::FLOG2, VT, Action);
575     setOperationAction(ISD::FLOG10, VT, Action);
576     setOperationAction(ISD::FEXP, VT, Action);
577     setOperationAction(ISD::FEXP2, VT, Action);
578     setOperationAction(ISD::FCEIL, VT, Action);
579     setOperationAction(ISD::FFLOOR, VT, Action);
580     setOperationAction(ISD::FNEARBYINT, VT, Action);
581     setOperationAction(ISD::FRINT, VT, Action);
582     setOperationAction(ISD::BR_CC, VT, Action);
583     setOperationAction(ISD::SETCC, VT, Action);
584     setOperationAction(ISD::SELECT, VT, Custom);
585     setOperationAction(ISD::SELECT_CC, VT, Action);
586     setOperationAction(ISD::FROUND, VT, Action);
587     setOperationAction(ISD::FROUNDEVEN, VT, Action);
588     setOperationAction(ISD::FTRUNC, VT, Action);
589   };
590 
591   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
592     // f16, f32 and f64 use SSE.
593     // Set up the FP register classes.
594     addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
595                                                      : &X86::FR16RegClass);
596     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
597                                                      : &X86::FR32RegClass);
598     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
599                                                      : &X86::FR64RegClass);
600 
601     // Disable f32->f64 extload as we can only generate this in one instruction
602     // under optsize. So its easier to pattern match (fpext (load)) for that
603     // case instead of needing to emit 2 instructions for extload in the
604     // non-optsize case.
605     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
606 
607     for (auto VT : { MVT::f32, MVT::f64 }) {
608       // Use ANDPD to simulate FABS.
609       setOperationAction(ISD::FABS, VT, Custom);
610 
611       // Use XORP to simulate FNEG.
612       setOperationAction(ISD::FNEG, VT, Custom);
613 
614       // Use ANDPD and ORPD to simulate FCOPYSIGN.
615       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
616 
617       // These might be better off as horizontal vector ops.
618       setOperationAction(ISD::FADD, VT, Custom);
619       setOperationAction(ISD::FSUB, VT, Custom);
620 
621       // We don't support sin/cos/fmod
622       setOperationAction(ISD::FSIN   , VT, Expand);
623       setOperationAction(ISD::FCOS   , VT, Expand);
624       setOperationAction(ISD::FSINCOS, VT, Expand);
625     }
626 
627     // Half type will be promoted by default.
628     setF16Action(MVT::f16, Promote);
629     setOperationAction(ISD::FADD, MVT::f16, Promote);
630     setOperationAction(ISD::FSUB, MVT::f16, Promote);
631     setOperationAction(ISD::FMUL, MVT::f16, Promote);
632     setOperationAction(ISD::FDIV, MVT::f16, Promote);
633     setOperationAction(ISD::FP_ROUND, MVT::f16, LibCall);
634     setOperationAction(ISD::FP_EXTEND, MVT::f32, LibCall);
635     setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
636 
637     setOperationAction(ISD::STRICT_FADD, MVT::f16, Promote);
638     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Promote);
639     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Promote);
640     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Promote);
641     setOperationAction(ISD::STRICT_FMA, MVT::f16, Promote);
642     setOperationAction(ISD::STRICT_FMINNUM, MVT::f16, Promote);
643     setOperationAction(ISD::STRICT_FMAXNUM, MVT::f16, Promote);
644     setOperationAction(ISD::STRICT_FMINIMUM, MVT::f16, Promote);
645     setOperationAction(ISD::STRICT_FMAXIMUM, MVT::f16, Promote);
646     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Promote);
647     setOperationAction(ISD::STRICT_FPOW, MVT::f16, Promote);
648     setOperationAction(ISD::STRICT_FLOG, MVT::f16, Promote);
649     setOperationAction(ISD::STRICT_FLOG2, MVT::f16, Promote);
650     setOperationAction(ISD::STRICT_FLOG10, MVT::f16, Promote);
651     setOperationAction(ISD::STRICT_FEXP, MVT::f16, Promote);
652     setOperationAction(ISD::STRICT_FEXP2, MVT::f16, Promote);
653     setOperationAction(ISD::STRICT_FCEIL, MVT::f16, Promote);
654     setOperationAction(ISD::STRICT_FFLOOR, MVT::f16, Promote);
655     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f16, Promote);
656     setOperationAction(ISD::STRICT_FRINT, MVT::f16, Promote);
657     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Promote);
658     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Promote);
659     setOperationAction(ISD::STRICT_FROUND, MVT::f16, Promote);
660     setOperationAction(ISD::STRICT_FROUNDEVEN, MVT::f16, Promote);
661     setOperationAction(ISD::STRICT_FTRUNC, MVT::f16, Promote);
662     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, LibCall);
663     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, LibCall);
664     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
665 
666     setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
667     setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
668 
669     // Lower this to MOVMSK plus an AND.
670     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
671     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
672 
673   } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
674              (UseX87 || Is64Bit)) {
675     // Use SSE for f32, x87 for f64.
676     // Set up the FP register classes.
677     addRegisterClass(MVT::f32, &X86::FR32RegClass);
678     if (UseX87)
679       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680 
681     // Use ANDPS to simulate FABS.
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683 
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f32, Custom);
686 
687     if (UseX87)
688       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
689 
690     // Use ANDPS and ORPS to simulate FCOPYSIGN.
691     if (UseX87)
692       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
693     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694 
695     // We don't support sin/cos/fmod
696     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
697     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
698     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699 
700     if (UseX87) {
701       // Always expand sin/cos functions even though x87 has an instruction.
702       setOperationAction(ISD::FSIN, MVT::f64, Expand);
703       setOperationAction(ISD::FCOS, MVT::f64, Expand);
704       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
705     }
706   } else if (UseX87) {
707     // f32 and f64 in x87.
708     // Set up the FP register classes.
709     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
710     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
711 
712     for (auto VT : { MVT::f32, MVT::f64 }) {
713       setOperationAction(ISD::UNDEF,     VT, Expand);
714       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
715 
716       // Always expand sin/cos functions even though x87 has an instruction.
717       setOperationAction(ISD::FSIN   , VT, Expand);
718       setOperationAction(ISD::FCOS   , VT, Expand);
719       setOperationAction(ISD::FSINCOS, VT, Expand);
720     }
721   }
722 
723   // Expand FP32 immediates into loads from the stack, save special cases.
724   if (isTypeLegal(MVT::f32)) {
725     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
726       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
727       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
728       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
729       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
730     } else // SSE immediates.
731       addLegalFPImmediate(APFloat(+0.0f)); // xorps
732   }
733   // Expand FP64 immediates into loads from the stack, save special cases.
734   if (isTypeLegal(MVT::f64)) {
735     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
736       addLegalFPImmediate(APFloat(+0.0)); // FLD0
737       addLegalFPImmediate(APFloat(+1.0)); // FLD1
738       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740     } else // SSE immediates.
741       addLegalFPImmediate(APFloat(+0.0)); // xorpd
742   }
743   // Support fp16 0 immediate.
744   if (isTypeLegal(MVT::f16))
745     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
746 
747   // Handle constrained floating-point operations of scalar.
748   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
749   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
750   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
751   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
752   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
753   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
754   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
755   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
756   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
757   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
758   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
759   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
760 
761   // We don't support FMA.
762   setOperationAction(ISD::FMA, MVT::f64, Expand);
763   setOperationAction(ISD::FMA, MVT::f32, Expand);
764 
765   // f80 always uses X87.
766   if (UseX87) {
767     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
768     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
769     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
770     {
771       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
772       addLegalFPImmediate(TmpFlt);  // FLD0
773       TmpFlt.changeSign();
774       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
775 
776       bool ignored;
777       APFloat TmpFlt2(+1.0);
778       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
779                       &ignored);
780       addLegalFPImmediate(TmpFlt2);  // FLD1
781       TmpFlt2.changeSign();
782       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
783     }
784 
785     // Always expand sin/cos functions even though x87 has an instruction.
786     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
787     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
788     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
789 
790     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
791     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
792     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
793     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
794     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
795     setOperationAction(ISD::FMA, MVT::f80, Expand);
796     setOperationAction(ISD::LROUND, MVT::f80, Expand);
797     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
798     setOperationAction(ISD::LRINT, MVT::f80, Custom);
799     setOperationAction(ISD::LLRINT, MVT::f80, Custom);
800 
801     // Handle constrained floating-point operations of scalar.
802     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
803     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
804     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
805     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
806     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
807     if (isTypeLegal(MVT::f16)) {
808       setOperationAction(ISD::FP_EXTEND, MVT::f80, Custom);
809       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Custom);
810     } else {
811       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
812     }
813     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
814     // as Custom.
815     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
816   }
817 
818   // f128 uses xmm registers, but most operations require libcalls.
819   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
820     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
821                                                    : &X86::VR128RegClass);
822 
823     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
824 
825     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
826     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
827     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
828     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
829     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
830     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
831     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
832     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
833     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
834     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
835 
836     setOperationAction(ISD::FABS, MVT::f128, Custom);
837     setOperationAction(ISD::FNEG, MVT::f128, Custom);
838     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
839 
840     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
841     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
842     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
843     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
844     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
845     // No STRICT_FSINCOS
846     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
847     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
848 
849     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
850     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
851     // We need to custom handle any FP_ROUND with an f128 input, but
852     // LegalizeDAG uses the result type to know when to run a custom handler.
853     // So we have to list all legal floating point result types here.
854     if (isTypeLegal(MVT::f32)) {
855       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
856       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
857     }
858     if (isTypeLegal(MVT::f64)) {
859       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
860       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
861     }
862     if (isTypeLegal(MVT::f80)) {
863       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
864       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
865     }
866 
867     setOperationAction(ISD::SETCC, MVT::f128, Custom);
868 
869     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
870     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
871     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
872     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
873     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
874     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
875   }
876 
877   // Always use a library call for pow.
878   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
879   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
880   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
881   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
882 
883   setOperationAction(ISD::FLOG, MVT::f80, Expand);
884   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
885   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
886   setOperationAction(ISD::FEXP, MVT::f80, Expand);
887   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
888   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
889   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
890 
891   // Some FP actions are always expanded for vector types.
892   for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
893                    MVT::v4f32, MVT::v8f32,  MVT::v16f32,
894                    MVT::v2f64, MVT::v4f64,  MVT::v8f64 }) {
895     setOperationAction(ISD::FSIN,      VT, Expand);
896     setOperationAction(ISD::FSINCOS,   VT, Expand);
897     setOperationAction(ISD::FCOS,      VT, Expand);
898     setOperationAction(ISD::FREM,      VT, Expand);
899     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
900     setOperationAction(ISD::FPOW,      VT, Expand);
901     setOperationAction(ISD::FLOG,      VT, Expand);
902     setOperationAction(ISD::FLOG2,     VT, Expand);
903     setOperationAction(ISD::FLOG10,    VT, Expand);
904     setOperationAction(ISD::FEXP,      VT, Expand);
905     setOperationAction(ISD::FEXP2,     VT, Expand);
906   }
907 
908   // First set operation action for all vector types to either promote
909   // (for widening) or expand (for scalarization). Then we will selectively
910   // turn on ones that can be effectively codegen'd.
911   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
912     setOperationAction(ISD::SDIV, VT, Expand);
913     setOperationAction(ISD::UDIV, VT, Expand);
914     setOperationAction(ISD::SREM, VT, Expand);
915     setOperationAction(ISD::UREM, VT, Expand);
916     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
917     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
918     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
919     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
920     setOperationAction(ISD::FMA,  VT, Expand);
921     setOperationAction(ISD::FFLOOR, VT, Expand);
922     setOperationAction(ISD::FCEIL, VT, Expand);
923     setOperationAction(ISD::FTRUNC, VT, Expand);
924     setOperationAction(ISD::FRINT, VT, Expand);
925     setOperationAction(ISD::FNEARBYINT, VT, Expand);
926     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
927     setOperationAction(ISD::MULHS, VT, Expand);
928     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
929     setOperationAction(ISD::MULHU, VT, Expand);
930     setOperationAction(ISD::SDIVREM, VT, Expand);
931     setOperationAction(ISD::UDIVREM, VT, Expand);
932     setOperationAction(ISD::CTPOP, VT, Expand);
933     setOperationAction(ISD::CTTZ, VT, Expand);
934     setOperationAction(ISD::CTLZ, VT, Expand);
935     setOperationAction(ISD::ROTL, VT, Expand);
936     setOperationAction(ISD::ROTR, VT, Expand);
937     setOperationAction(ISD::BSWAP, VT, Expand);
938     setOperationAction(ISD::SETCC, VT, Expand);
939     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
940     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
941     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
942     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
943     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
944     setOperationAction(ISD::TRUNCATE, VT, Expand);
945     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
946     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
947     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
948     setOperationAction(ISD::SELECT_CC, VT, Expand);
949     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
950       setTruncStoreAction(InnerVT, VT, Expand);
951 
952       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
953       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
954 
955       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
956       // types, we have to deal with them whether we ask for Expansion or not.
957       // Setting Expand causes its own optimisation problems though, so leave
958       // them legal.
959       if (VT.getVectorElementType() == MVT::i1)
960         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
961 
962       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
963       // split/scalarized right now.
964       if (VT.getVectorElementType() == MVT::f16 ||
965           VT.getVectorElementType() == MVT::bf16)
966         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
967     }
968   }
969 
970   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
971   // with -msoft-float, disable use of MMX as well.
972   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
973     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
974     // No operations on x86mmx supported, everything uses intrinsics.
975   }
976 
977   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
978     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
979                                                     : &X86::VR128RegClass);
980 
981     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
982     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
983     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
986     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
988     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
989 
990     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
991     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
992 
993     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
994     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
995     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
996     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
997     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
998   }
999 
1000   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1001     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1002                                                     : &X86::VR128RegClass);
1003 
1004     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1005     // registers cannot be used even for integer operations.
1006     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1007                                                     : &X86::VR128RegClass);
1008     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1009                                                     : &X86::VR128RegClass);
1010     addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1011                                                     : &X86::VR128RegClass);
1012     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1013                                                     : &X86::VR128RegClass);
1014     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1015                                                     : &X86::VR128RegClass);
1016 
1017     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
1018                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
1019       setOperationAction(ISD::SDIV, VT, Custom);
1020       setOperationAction(ISD::SREM, VT, Custom);
1021       setOperationAction(ISD::UDIV, VT, Custom);
1022       setOperationAction(ISD::UREM, VT, Custom);
1023     }
1024 
1025     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
1026     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
1027     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
1028 
1029     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
1030     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
1031     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
1032     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
1033     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
1034     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
1035     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
1036     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
1037     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
1038     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
1039     setOperationAction(ISD::AVGCEILU,           MVT::v16i8, Legal);
1040     setOperationAction(ISD::AVGCEILU,           MVT::v8i16, Legal);
1041 
1042     setOperationAction(ISD::SMULO,              MVT::v16i8, Custom);
1043     setOperationAction(ISD::UMULO,              MVT::v16i8, Custom);
1044     setOperationAction(ISD::UMULO,              MVT::v2i32, Custom);
1045 
1046     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
1047     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
1048     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
1049 
1050     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1051       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1052       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1053       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1054       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1055     }
1056 
1057     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
1058     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
1059     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
1060     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
1061     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
1062     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
1063     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
1064     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
1065     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
1066     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
1067 
1068     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1069     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1070     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1071     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1072 
1073     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1074       setOperationAction(ISD::SETCC,              VT, Custom);
1075       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
1076       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
1077       setOperationAction(ISD::CTPOP,              VT, Custom);
1078       setOperationAction(ISD::ABS,                VT, Custom);
1079 
1080       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1081       // setcc all the way to isel and prefer SETGT in some isel patterns.
1082       setCondCodeAction(ISD::SETLT, VT, Custom);
1083       setCondCodeAction(ISD::SETLE, VT, Custom);
1084     }
1085 
1086     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1087       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1088       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1089       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1090       setOperationAction(ISD::VSELECT,            VT, Custom);
1091       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1092     }
1093 
1094     for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1095       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1096       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1097       setOperationAction(ISD::VSELECT,            VT, Custom);
1098 
1099       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1100         continue;
1101 
1102       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1103       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1104     }
1105     setF16Action(MVT::v8f16, Expand);
1106     setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1107     setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1108     setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1109     setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1110 
1111     // Custom lower v2i64 and v2f64 selects.
1112     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1113     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1114     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
1115     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
1116     setOperationAction(ISD::SELECT,             MVT::v8f16, Custom);
1117     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
1118 
1119     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Custom);
1120     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Custom);
1121     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
1122     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1123     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Custom);
1124     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
1125 
1126     // Custom legalize these to avoid over promotion or custom promotion.
1127     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1128       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1129       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1130       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1131       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1132     }
1133 
1134     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Custom);
1135     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Custom);
1136     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
1137     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
1138 
1139     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
1140     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
1141 
1142     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
1143     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
1144 
1145     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1146     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
1147     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
1148     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
1149     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
1150 
1151     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1152     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
1153     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1154     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1155 
1156     // We want to legalize this to an f64 load rather than an i64 load on
1157     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1158     // store.
1159     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1160     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1161     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1162     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1163     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1164     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1165 
1166     // Add 32-bit vector stores to help vectorization opportunities.
1167     setOperationAction(ISD::STORE,              MVT::v2i16, Custom);
1168     setOperationAction(ISD::STORE,              MVT::v4i8,  Custom);
1169 
1170     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1171     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1172     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1173     if (!Subtarget.hasAVX512())
1174       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1175 
1176     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1177     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1178     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1179 
1180     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1181 
1182     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1183     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1184     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1185     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1186     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1187     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1188 
1189     // In the customized shift lowering, the legal v4i32/v2i64 cases
1190     // in AVX2 will be recognized.
1191     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1192       setOperationAction(ISD::SRL,              VT, Custom);
1193       setOperationAction(ISD::SHL,              VT, Custom);
1194       setOperationAction(ISD::SRA,              VT, Custom);
1195       if (VT == MVT::v2i64) continue;
1196       setOperationAction(ISD::ROTL,             VT, Custom);
1197       setOperationAction(ISD::ROTR,             VT, Custom);
1198       setOperationAction(ISD::FSHL,             VT, Custom);
1199       setOperationAction(ISD::FSHR,             VT, Custom);
1200     }
1201 
1202     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1203     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1204     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1205     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1206     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1207   }
1208 
1209   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1210     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1211     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1212     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1213     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1214     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1215     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1216     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1217     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1218 
1219     // These might be better off as horizontal vector ops.
1220     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1221     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1222     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1223     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1224   }
1225 
1226   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1227     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1228       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1229       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1230       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1231       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1232       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1233       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1234       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1235       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1236       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1237       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1238       setOperationAction(ISD::FROUNDEVEN,        RoundedTy,  Legal);
1239       setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy,  Legal);
1240 
1241       setOperationAction(ISD::FROUND,            RoundedTy,  Custom);
1242     }
1243 
1244     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1245     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1246     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1247     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1248     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1249     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1250     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1251     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1252 
1253     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
1254     setOperationAction(ISD::SADDSAT,            MVT::v2i64, Custom);
1255     setOperationAction(ISD::SSUBSAT,            MVT::v2i64, Custom);
1256 
1257     // FIXME: Do we need to handle scalar-to-vector here?
1258     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1259     setOperationAction(ISD::SMULO,              MVT::v2i32, Custom);
1260 
1261     // We directly match byte blends in the backend as they match the VSELECT
1262     // condition form.
1263     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1264 
1265     // SSE41 brings specific instructions for doing vector sign extend even in
1266     // cases where we don't have SRA.
1267     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1268       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1269       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1270     }
1271 
1272     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1273     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1274       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1275       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1276       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1277       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1278       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1279       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1280     }
1281 
1282     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1283       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1284       // do the pre and post work in the vector domain.
1285       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1286       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1287       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1288       // so that DAG combine doesn't try to turn it into uint_to_fp.
1289       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1290       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1291     }
1292   }
1293 
1294   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1295     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
1296   }
1297 
1298   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1299     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1300                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1301       setOperationAction(ISD::ROTL, VT, Custom);
1302       setOperationAction(ISD::ROTR, VT, Custom);
1303     }
1304 
1305     // XOP can efficiently perform BITREVERSE with VPPERM.
1306     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1307       setOperationAction(ISD::BITREVERSE, VT, Custom);
1308 
1309     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1310                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1311       setOperationAction(ISD::BITREVERSE, VT, Custom);
1312   }
1313 
1314   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1315     bool HasInt256 = Subtarget.hasInt256();
1316 
1317     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1318                                                      : &X86::VR256RegClass);
1319     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1320                                                      : &X86::VR256RegClass);
1321     addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1322                                                      : &X86::VR256RegClass);
1323     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1324                                                      : &X86::VR256RegClass);
1325     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1326                                                      : &X86::VR256RegClass);
1327     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1328                                                      : &X86::VR256RegClass);
1329     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1330                                                      : &X86::VR256RegClass);
1331 
1332     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1333       setOperationAction(ISD::FFLOOR,            VT, Legal);
1334       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1335       setOperationAction(ISD::FCEIL,             VT, Legal);
1336       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1337       setOperationAction(ISD::FTRUNC,            VT, Legal);
1338       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1339       setOperationAction(ISD::FRINT,             VT, Legal);
1340       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1341       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1342       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1343       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1344       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1345 
1346       setOperationAction(ISD::FROUND,            VT, Custom);
1347 
1348       setOperationAction(ISD::FNEG,              VT, Custom);
1349       setOperationAction(ISD::FABS,              VT, Custom);
1350       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1351     }
1352 
1353     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1354     // even though v8i16 is a legal type.
1355     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1356     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1357     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1358     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1359     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Custom);
1360     setOperationAction(ISD::FP_TO_UINT,                MVT::v8i32, Custom);
1361     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Custom);
1362 
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Custom);
1364     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Custom);
1365     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Expand);
1366     setOperationAction(ISD::FP_ROUND,           MVT::v8f16, Expand);
1367     setOperationAction(ISD::FP_EXTEND,          MVT::v4f64, Custom);
1368     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Custom);
1369 
1370     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1371     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1372     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1373     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1374     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1375     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1376     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1377     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1378     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1379     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1380     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1381 
1382     if (!Subtarget.hasAVX512())
1383       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1384 
1385     // In the customized shift lowering, the legal v8i32/v4i64 cases
1386     // in AVX2 will be recognized.
1387     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1388       setOperationAction(ISD::SRL, VT, Custom);
1389       setOperationAction(ISD::SHL, VT, Custom);
1390       setOperationAction(ISD::SRA, VT, Custom);
1391       if (VT == MVT::v4i64) continue;
1392       setOperationAction(ISD::ROTL, VT, Custom);
1393       setOperationAction(ISD::ROTR, VT, Custom);
1394       setOperationAction(ISD::FSHL, VT, Custom);
1395       setOperationAction(ISD::FSHR, VT, Custom);
1396     }
1397 
1398     // These types need custom splitting if their input is a 128-bit vector.
1399     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1400     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1401     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1402     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1403 
1404     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1405     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1406     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1407     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1408     setOperationAction(ISD::SELECT,            MVT::v16f16, Custom);
1409     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1410     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1411 
1412     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1413       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1414       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1415       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1416     }
1417 
1418     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1419     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1420     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1421     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1422 
1423     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1424       setOperationAction(ISD::SETCC,           VT, Custom);
1425       setOperationAction(ISD::STRICT_FSETCC,   VT, Custom);
1426       setOperationAction(ISD::STRICT_FSETCCS,  VT, Custom);
1427       setOperationAction(ISD::CTPOP,           VT, Custom);
1428       setOperationAction(ISD::CTLZ,            VT, Custom);
1429 
1430       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1431       // setcc all the way to isel and prefer SETGT in some isel patterns.
1432       setCondCodeAction(ISD::SETLT, VT, Custom);
1433       setCondCodeAction(ISD::SETLE, VT, Custom);
1434     }
1435 
1436     if (Subtarget.hasAnyFMA()) {
1437       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1438                        MVT::v2f64, MVT::v4f64 }) {
1439         setOperationAction(ISD::FMA, VT, Legal);
1440         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1441       }
1442     }
1443 
1444     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1445       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1446       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1447     }
1448 
1449     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1450     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1451     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1452     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1453 
1454     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1455     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1456     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1457     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1458     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1459     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1460     setOperationAction(ISD::AVGCEILU,  MVT::v16i16, HasInt256 ? Legal : Custom);
1461     setOperationAction(ISD::AVGCEILU,  MVT::v32i8,  HasInt256 ? Legal : Custom);
1462 
1463     setOperationAction(ISD::SMULO,     MVT::v32i8, Custom);
1464     setOperationAction(ISD::UMULO,     MVT::v32i8, Custom);
1465 
1466     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1467     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1468     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1469     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1470     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1471 
1472     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1473     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1474     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1475     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1476     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1477     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1478     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1479     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1480     setOperationAction(ISD::UADDSAT,   MVT::v8i32, Custom);
1481     setOperationAction(ISD::USUBSAT,   MVT::v8i32, Custom);
1482     setOperationAction(ISD::UADDSAT,   MVT::v4i64, Custom);
1483     setOperationAction(ISD::USUBSAT,   MVT::v4i64, Custom);
1484 
1485     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1486       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1487       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1488       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1489       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1490       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1491     }
1492 
1493     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1494       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1495       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1496     }
1497 
1498     if (HasInt256) {
1499       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1500       // when we have a 256bit-wide blend with immediate.
1501       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1502       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1503 
1504       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1505       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1506         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1507         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1508         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1509         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1510         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1511         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1512       }
1513     }
1514 
1515     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1516                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1517       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1518       setOperationAction(ISD::MSTORE, VT, Legal);
1519     }
1520 
1521     // Extract subvector is special because the value type
1522     // (result) is 128-bit but the source is 256-bit wide.
1523     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1524                      MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1525       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1526     }
1527 
1528     // Custom lower several nodes for 256-bit types.
1529     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1530                     MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1531       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1532       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1533       setOperationAction(ISD::VSELECT,            VT, Custom);
1534       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1535       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1536       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1537       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1538       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1539       setOperationAction(ISD::STORE,              VT, Custom);
1540     }
1541     setF16Action(MVT::v16f16, Expand);
1542     setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1543     setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1544     setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1545     setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1546 
1547     if (HasInt256) {
1548       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1549 
1550       // Custom legalize 2x32 to get a little better code.
1551       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1552       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1553 
1554       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1555                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1556         setOperationAction(ISD::MGATHER,  VT, Custom);
1557     }
1558   }
1559 
1560   if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1561       Subtarget.hasF16C()) {
1562     for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1563       setOperationAction(ISD::FP_ROUND,           VT, Custom);
1564       setOperationAction(ISD::STRICT_FP_ROUND,    VT, Custom);
1565     }
1566     for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32 }) {
1567       setOperationAction(ISD::FP_EXTEND,          VT, Custom);
1568       setOperationAction(ISD::STRICT_FP_EXTEND,   VT, Custom);
1569     }
1570     for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1571       setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1572       setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1573     }
1574 
1575     setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1576     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f32, Legal);
1577   }
1578 
1579   // This block controls legalization of the mask vector sizes that are
1580   // available with AVX512. 512-bit vectors are in a separate block controlled
1581   // by useAVX512Regs.
1582   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1583     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1584     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1585     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1586     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1587     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1588 
1589     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1590     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1591     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1592 
1593     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1594     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1595     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1596     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1597     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1598     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1599     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1600     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1601     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1602     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1603     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1604     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1605 
1606     // There is no byte sized k-register load or store without AVX512DQ.
1607     if (!Subtarget.hasDQI()) {
1608       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1609       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1610       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1611       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1612 
1613       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1614       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1615       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1616       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1617     }
1618 
1619     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1620     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1621       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1622       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1623       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1624     }
1625 
1626     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1627       setOperationAction(ISD::VSELECT,          VT, Expand);
1628 
1629     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1630       setOperationAction(ISD::SETCC,            VT, Custom);
1631       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1632       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1633       setOperationAction(ISD::SELECT,           VT, Custom);
1634       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1635 
1636       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1637       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1638       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1639       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1640       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1641       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1642     }
1643 
1644     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1645       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1646   }
1647 
1648   // This block controls legalization for 512-bit operations with 32/64 bit
1649   // elements. 512-bits can be disabled based on prefer-vector-width and
1650   // required-vector-width function attributes.
1651   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1652     bool HasBWI = Subtarget.hasBWI();
1653 
1654     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1655     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1656     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1657     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1658     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1659     addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1660     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1661 
1662     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1663       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1664       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1665       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1666       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1667       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1668       if (HasBWI)
1669         setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1670     }
1671 
1672     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1673       setOperationAction(ISD::FNEG,  VT, Custom);
1674       setOperationAction(ISD::FABS,  VT, Custom);
1675       setOperationAction(ISD::FMA,   VT, Legal);
1676       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1677       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1678     }
1679 
1680     for (MVT VT : { MVT::v16i1, MVT::v16i8, MVT::v16i16 }) {
1681       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1682       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1683       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1684       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1685     }
1686     setOperationAction(ISD::FP_TO_SINT,        MVT::v16i32, Custom);
1687     setOperationAction(ISD::FP_TO_UINT,        MVT::v16i32, Custom);
1688     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v16i32, Custom);
1689     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v16i32, Custom);
1690     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Custom);
1691     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Custom);
1692     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Custom);
1693     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Custom);
1694     setOperationAction(ISD::FP_EXTEND,         MVT::v8f64,  Custom);
1695     setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v8f64,  Custom);
1696 
1697     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1698     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1699     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1700     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1701     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1702     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1703     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1704     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1705     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1706     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1707     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1708 
1709     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1710     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1711     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1712     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1713     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1714     if (HasBWI)
1715       setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1716 
1717     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1718     // to 512-bit rather than use the AVX2 instructions so that we can use
1719     // k-masks.
1720     if (!Subtarget.hasVLX()) {
1721       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1722            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1723         setOperationAction(ISD::MLOAD,  VT, Custom);
1724         setOperationAction(ISD::MSTORE, VT, Custom);
1725       }
1726     }
1727 
1728     setOperationAction(ISD::TRUNCATE,    MVT::v8i32,  Legal);
1729     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Legal);
1730     setOperationAction(ISD::TRUNCATE,    MVT::v32i8,  HasBWI ? Legal : Custom);
1731     setOperationAction(ISD::TRUNCATE,    MVT::v16i64, Custom);
1732     setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1733     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1734     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
1735     setOperationAction(ISD::ANY_EXTEND,  MVT::v32i16, Custom);
1736     setOperationAction(ISD::ANY_EXTEND,  MVT::v16i32, Custom);
1737     setOperationAction(ISD::ANY_EXTEND,  MVT::v8i64,  Custom);
1738     setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1739     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1740     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
1741 
1742     if (HasBWI) {
1743       // Extends from v64i1 masks to 512-bit vectors.
1744       setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1745       setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1746       setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1747     }
1748 
1749     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1750       setOperationAction(ISD::FFLOOR,            VT, Legal);
1751       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1752       setOperationAction(ISD::FCEIL,             VT, Legal);
1753       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1754       setOperationAction(ISD::FTRUNC,            VT, Legal);
1755       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1756       setOperationAction(ISD::FRINT,             VT, Legal);
1757       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1758       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1759       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1760       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1761       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1762 
1763       setOperationAction(ISD::FROUND,            VT, Custom);
1764     }
1765 
1766     for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1767       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1768       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1769     }
1770 
1771     setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1772     setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1773     setOperationAction(ISD::ADD, MVT::v64i8,  HasBWI ? Legal : Custom);
1774     setOperationAction(ISD::SUB, MVT::v64i8,  HasBWI ? Legal : Custom);
1775 
1776     setOperationAction(ISD::MUL, MVT::v8i64,  Custom);
1777     setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1778     setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1779     setOperationAction(ISD::MUL, MVT::v64i8,  Custom);
1780 
1781     setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1782     setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1783     setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1784     setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1785     setOperationAction(ISD::MULHS, MVT::v64i8,  Custom);
1786     setOperationAction(ISD::MULHU, MVT::v64i8,  Custom);
1787     setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
1788     setOperationAction(ISD::AVGCEILU, MVT::v64i8,  HasBWI ? Legal : Custom);
1789 
1790     setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1791     setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1792 
1793     setOperationAction(ISD::BITREVERSE, MVT::v64i8,  Custom);
1794 
1795     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1796       setOperationAction(ISD::SRL,              VT, Custom);
1797       setOperationAction(ISD::SHL,              VT, Custom);
1798       setOperationAction(ISD::SRA,              VT, Custom);
1799       setOperationAction(ISD::ROTL,             VT, Custom);
1800       setOperationAction(ISD::ROTR,             VT, Custom);
1801       setOperationAction(ISD::SETCC,            VT, Custom);
1802 
1803       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1804       // setcc all the way to isel and prefer SETGT in some isel patterns.
1805       setCondCodeAction(ISD::SETLT, VT, Custom);
1806       setCondCodeAction(ISD::SETLE, VT, Custom);
1807     }
1808     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1809       setOperationAction(ISD::SMAX,             VT, Legal);
1810       setOperationAction(ISD::UMAX,             VT, Legal);
1811       setOperationAction(ISD::SMIN,             VT, Legal);
1812       setOperationAction(ISD::UMIN,             VT, Legal);
1813       setOperationAction(ISD::ABS,              VT, Legal);
1814       setOperationAction(ISD::CTPOP,            VT, Custom);
1815       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1816       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1817     }
1818 
1819     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1820       setOperationAction(ISD::ABS,     VT, HasBWI ? Legal : Custom);
1821       setOperationAction(ISD::CTPOP,   VT, Subtarget.hasBITALG() ? Legal : Custom);
1822       setOperationAction(ISD::CTLZ,    VT, Custom);
1823       setOperationAction(ISD::SMAX,    VT, HasBWI ? Legal : Custom);
1824       setOperationAction(ISD::UMAX,    VT, HasBWI ? Legal : Custom);
1825       setOperationAction(ISD::SMIN,    VT, HasBWI ? Legal : Custom);
1826       setOperationAction(ISD::UMIN,    VT, HasBWI ? Legal : Custom);
1827       setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1828       setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1829       setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1830       setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1831     }
1832 
1833     setOperationAction(ISD::FSHL,       MVT::v64i8, Custom);
1834     setOperationAction(ISD::FSHR,       MVT::v64i8, Custom);
1835     setOperationAction(ISD::FSHL,      MVT::v32i16, Custom);
1836     setOperationAction(ISD::FSHR,      MVT::v32i16, Custom);
1837     setOperationAction(ISD::FSHL,      MVT::v16i32, Custom);
1838     setOperationAction(ISD::FSHR,      MVT::v16i32, Custom);
1839 
1840     if (Subtarget.hasDQI()) {
1841       for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
1842                        ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1843                        ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT})
1844         setOperationAction(Opc,           MVT::v8i64, Custom);
1845       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1846     }
1847 
1848     if (Subtarget.hasCDI()) {
1849       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1850       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1851         setOperationAction(ISD::CTLZ,            VT, Legal);
1852       }
1853     } // Subtarget.hasCDI()
1854 
1855     if (Subtarget.hasVPOPCNTDQ()) {
1856       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1857         setOperationAction(ISD::CTPOP, VT, Legal);
1858     }
1859 
1860     // Extract subvector is special because the value type
1861     // (result) is 256-bit but the source is 512-bit wide.
1862     // 128-bit was made Legal under AVX1.
1863     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1864                      MVT::v16f16, MVT::v8f32, MVT::v4f64 })
1865       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1866 
1867     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1868                      MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
1869       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1870       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1871       setOperationAction(ISD::SELECT,             VT, Custom);
1872       setOperationAction(ISD::VSELECT,            VT, Custom);
1873       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1874       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1875       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1876       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1877       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1878     }
1879     setF16Action(MVT::v32f16, Expand);
1880     setOperationAction(ISD::FP_ROUND, MVT::v16f16, Custom);
1881     setOperationAction(ISD::STRICT_FP_ROUND, MVT::v16f16, Custom);
1882     setOperationAction(ISD::FP_EXTEND, MVT::v16f32, Legal);
1883     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v16f32, Legal);
1884     for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1885       setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1886       setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
1887     }
1888 
1889     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1890       setOperationAction(ISD::MLOAD,               VT, Legal);
1891       setOperationAction(ISD::MSTORE,              VT, Legal);
1892       setOperationAction(ISD::MGATHER,             VT, Custom);
1893       setOperationAction(ISD::MSCATTER,            VT, Custom);
1894     }
1895     if (HasBWI) {
1896       for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1897         setOperationAction(ISD::MLOAD,        VT, Legal);
1898         setOperationAction(ISD::MSTORE,       VT, Legal);
1899       }
1900     } else {
1901       setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1902       setOperationAction(ISD::STORE, MVT::v64i8,  Custom);
1903     }
1904 
1905     if (Subtarget.hasVBMI2()) {
1906       for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1907                        MVT::v16i16, MVT::v8i32, MVT::v4i64,
1908                        MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1909         setOperationAction(ISD::FSHL, VT, Custom);
1910         setOperationAction(ISD::FSHR, VT, Custom);
1911       }
1912 
1913       setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
1914       setOperationAction(ISD::ROTR, MVT::v8i16,  Custom);
1915       setOperationAction(ISD::ROTR, MVT::v16i16, Custom);
1916       setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
1917     }
1918   }// useAVX512Regs
1919 
1920   // This block controls legalization for operations that don't have
1921   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1922   // narrower widths.
1923   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1924     // These operations are handled on non-VLX by artificially widening in
1925     // isel patterns.
1926 
1927     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i32, Custom);
1928     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v4i32, Custom);
1929     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
1930 
1931     if (Subtarget.hasDQI()) {
1932       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1933       // v2f32 UINT_TO_FP is already custom under SSE2.
1934       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
1935              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
1936              "Unexpected operation action!");
1937       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1938       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
1939       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
1940       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
1941       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
1942     }
1943 
1944     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1945       setOperationAction(ISD::SMAX, VT, Legal);
1946       setOperationAction(ISD::UMAX, VT, Legal);
1947       setOperationAction(ISD::SMIN, VT, Legal);
1948       setOperationAction(ISD::UMIN, VT, Legal);
1949       setOperationAction(ISD::ABS,  VT, Legal);
1950     }
1951 
1952     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1953       setOperationAction(ISD::ROTL,     VT, Custom);
1954       setOperationAction(ISD::ROTR,     VT, Custom);
1955     }
1956 
1957     // Custom legalize 2x32 to get a little better code.
1958     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1959     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1960 
1961     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1962                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1963       setOperationAction(ISD::MSCATTER, VT, Custom);
1964 
1965     if (Subtarget.hasDQI()) {
1966       for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
1967                        ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1968                        ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT}) {
1969         setOperationAction(Opc, MVT::v2i64, Custom);
1970         setOperationAction(Opc, MVT::v4i64, Custom);
1971       }
1972       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1973       setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1974     }
1975 
1976     if (Subtarget.hasCDI()) {
1977       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1978         setOperationAction(ISD::CTLZ,            VT, Legal);
1979       }
1980     } // Subtarget.hasCDI()
1981 
1982     if (Subtarget.hasVPOPCNTDQ()) {
1983       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1984         setOperationAction(ISD::CTPOP, VT, Legal);
1985     }
1986   }
1987 
1988   // This block control legalization of v32i1/v64i1 which are available with
1989   // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1990   // useBWIRegs.
1991   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1992     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1993     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1994 
1995     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1996       setOperationAction(ISD::VSELECT,            VT, Expand);
1997       setOperationAction(ISD::TRUNCATE,           VT, Custom);
1998       setOperationAction(ISD::SETCC,              VT, Custom);
1999       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2000       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
2001       setOperationAction(ISD::SELECT,             VT, Custom);
2002       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
2003       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
2004       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
2005       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
2006     }
2007 
2008     for (auto VT : { MVT::v16i1, MVT::v32i1 })
2009       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
2010 
2011     // Extends from v32i1 masks to 256-bit vectors.
2012     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
2013     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
2014     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
2015 
2016     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
2017       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
2018       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2019     }
2020 
2021     // These operations are handled on non-VLX by artificially widening in
2022     // isel patterns.
2023     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2024 
2025     if (Subtarget.hasBITALG()) {
2026       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2027         setOperationAction(ISD::CTPOP, VT, Legal);
2028     }
2029   }
2030 
2031   if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2032     auto setGroup = [&] (MVT VT) {
2033       setOperationAction(ISD::FADD,               VT, Legal);
2034       setOperationAction(ISD::STRICT_FADD,        VT, Legal);
2035       setOperationAction(ISD::FSUB,               VT, Legal);
2036       setOperationAction(ISD::STRICT_FSUB,        VT, Legal);
2037       setOperationAction(ISD::FMUL,               VT, Legal);
2038       setOperationAction(ISD::STRICT_FMUL,        VT, Legal);
2039       setOperationAction(ISD::FDIV,               VT, Legal);
2040       setOperationAction(ISD::STRICT_FDIV,        VT, Legal);
2041       setOperationAction(ISD::FSQRT,              VT, Legal);
2042       setOperationAction(ISD::STRICT_FSQRT,       VT, Legal);
2043 
2044       setOperationAction(ISD::FFLOOR,             VT, Legal);
2045       setOperationAction(ISD::STRICT_FFLOOR,      VT, Legal);
2046       setOperationAction(ISD::FCEIL,              VT, Legal);
2047       setOperationAction(ISD::STRICT_FCEIL,       VT, Legal);
2048       setOperationAction(ISD::FTRUNC,             VT, Legal);
2049       setOperationAction(ISD::STRICT_FTRUNC,      VT, Legal);
2050       setOperationAction(ISD::FRINT,              VT, Legal);
2051       setOperationAction(ISD::STRICT_FRINT,       VT, Legal);
2052       setOperationAction(ISD::FNEARBYINT,         VT, Legal);
2053       setOperationAction(ISD::STRICT_FNEARBYINT,  VT, Legal);
2054 
2055       setOperationAction(ISD::LOAD,               VT, Legal);
2056       setOperationAction(ISD::STORE,              VT, Legal);
2057 
2058       setOperationAction(ISD::FMA,                VT, Legal);
2059       setOperationAction(ISD::STRICT_FMA,         VT, Legal);
2060       setOperationAction(ISD::VSELECT,            VT, Legal);
2061       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
2062       setOperationAction(ISD::SELECT,             VT, Custom);
2063 
2064       setOperationAction(ISD::FNEG,               VT, Custom);
2065       setOperationAction(ISD::FABS,               VT, Custom);
2066       setOperationAction(ISD::FCOPYSIGN,          VT, Custom);
2067       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2068       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
2069     };
2070 
2071     // AVX512_FP16 scalar operations
2072     setGroup(MVT::f16);
2073     setOperationAction(ISD::FREM,                 MVT::f16, Promote);
2074     setOperationAction(ISD::STRICT_FREM,          MVT::f16, Promote);
2075     setOperationAction(ISD::SELECT_CC,            MVT::f16, Expand);
2076     setOperationAction(ISD::BR_CC,                MVT::f16, Expand);
2077     setOperationAction(ISD::SETCC,                MVT::f16, Custom);
2078     setOperationAction(ISD::STRICT_FSETCC,        MVT::f16, Custom);
2079     setOperationAction(ISD::STRICT_FSETCCS,       MVT::f16, Custom);
2080     setOperationAction(ISD::FROUND,               MVT::f16, Custom);
2081     setOperationAction(ISD::STRICT_FROUND,        MVT::f16, Promote);
2082     setOperationAction(ISD::FROUNDEVEN,           MVT::f16, Legal);
2083     setOperationAction(ISD::STRICT_FROUNDEVEN,    MVT::f16, Legal);
2084     setOperationAction(ISD::FP_ROUND,             MVT::f16, Custom);
2085     setOperationAction(ISD::STRICT_FP_ROUND,      MVT::f16, Custom);
2086     setOperationAction(ISD::FP_EXTEND,            MVT::f32, Legal);
2087     setOperationAction(ISD::STRICT_FP_EXTEND,     MVT::f32, Legal);
2088 
2089     setCondCodeAction(ISD::SETOEQ, MVT::f16, Expand);
2090     setCondCodeAction(ISD::SETUNE, MVT::f16, Expand);
2091 
2092     if (Subtarget.useAVX512Regs()) {
2093       setGroup(MVT::v32f16);
2094       setOperationAction(ISD::SCALAR_TO_VECTOR,       MVT::v32f16, Custom);
2095       setOperationAction(ISD::SINT_TO_FP,             MVT::v32i16, Legal);
2096       setOperationAction(ISD::STRICT_SINT_TO_FP,      MVT::v32i16, Legal);
2097       setOperationAction(ISD::UINT_TO_FP,             MVT::v32i16, Legal);
2098       setOperationAction(ISD::STRICT_UINT_TO_FP,      MVT::v32i16, Legal);
2099       setOperationAction(ISD::FP_ROUND,               MVT::v16f16, Legal);
2100       setOperationAction(ISD::STRICT_FP_ROUND,        MVT::v16f16, Legal);
2101       setOperationAction(ISD::FP_EXTEND,              MVT::v16f32, Legal);
2102       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v16f32, Legal);
2103       setOperationAction(ISD::FP_EXTEND,              MVT::v8f64,  Legal);
2104       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v8f64,  Legal);
2105       setOperationAction(ISD::INSERT_VECTOR_ELT,      MVT::v32f16, Custom);
2106 
2107       setOperationAction(ISD::FP_TO_SINT,             MVT::v32i16, Custom);
2108       setOperationAction(ISD::STRICT_FP_TO_SINT,      MVT::v32i16, Custom);
2109       setOperationAction(ISD::FP_TO_UINT,             MVT::v32i16, Custom);
2110       setOperationAction(ISD::STRICT_FP_TO_UINT,      MVT::v32i16, Custom);
2111       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i8,  MVT::v32i16);
2112       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i8,
2113                                  MVT::v32i16);
2114       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i8,  MVT::v32i16);
2115       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i8,
2116                                  MVT::v32i16);
2117       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i1,  MVT::v32i16);
2118       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i1,
2119                                  MVT::v32i16);
2120       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i1,  MVT::v32i16);
2121       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i1,
2122                                  MVT::v32i16);
2123 
2124       setOperationAction(ISD::EXTRACT_SUBVECTOR,      MVT::v16f16, Legal);
2125       setOperationAction(ISD::INSERT_SUBVECTOR,       MVT::v32f16, Legal);
2126       setOperationAction(ISD::CONCAT_VECTORS,         MVT::v32f16, Custom);
2127 
2128       setLoadExtAction(ISD::EXTLOAD, MVT::v8f64,  MVT::v8f16,  Legal);
2129       setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2130 
2131       setOperationAction(ISD::STRICT_FSETCC,      MVT::v32i1, Custom);
2132       setOperationAction(ISD::STRICT_FSETCCS,     MVT::v32i1, Custom);
2133     }
2134 
2135     if (Subtarget.hasVLX()) {
2136       setGroup(MVT::v8f16);
2137       setGroup(MVT::v16f16);
2138 
2139       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8f16,  Legal);
2140       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16f16, Custom);
2141       setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Legal);
2142       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v16i16, Legal);
2143       setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16,  Legal);
2144       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i16,  Legal);
2145       setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Legal);
2146       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v16i16, Legal);
2147       setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16,  Legal);
2148       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v8i16,  Legal);
2149 
2150       setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
2151       setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v8i16, Custom);
2152       setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Custom);
2153       setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i16, Custom);
2154       setOperationAction(ISD::FP_ROUND,           MVT::v8f16, Legal);
2155       setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v8f16, Legal);
2156       setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
2157       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v8f32, Legal);
2158       setOperationAction(ISD::FP_EXTEND,          MVT::v4f64, Legal);
2159       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
2160 
2161       // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2162       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v8f16,  Custom);
2163       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v16f16, Custom);
2164 
2165       setOperationAction(ISD::EXTRACT_SUBVECTOR,    MVT::v8f16, Legal);
2166       setOperationAction(ISD::INSERT_SUBVECTOR,     MVT::v16f16, Legal);
2167       setOperationAction(ISD::CONCAT_VECTORS,       MVT::v16f16, Custom);
2168 
2169       setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2170       setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2171       setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2172       setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2173 
2174       // Need to custom widen these to prevent scalarization.
2175       setOperationAction(ISD::LOAD,  MVT::v4f16, Custom);
2176       setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2177     }
2178   }
2179 
2180   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2181     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
2182     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2183     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2184     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
2185     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2186 
2187     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
2188     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2189     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2190     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
2191     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2192 
2193     if (Subtarget.hasBWI()) {
2194       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
2195       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
2196     }
2197 
2198     if (Subtarget.hasFP16()) {
2199       // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2200       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f16, Custom);
2201       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f16, Custom);
2202       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f16, Custom);
2203       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f16, Custom);
2204       setOperationAction(ISD::FP_TO_SINT,        MVT::v4f16, Custom);
2205       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f16, Custom);
2206       setOperationAction(ISD::FP_TO_UINT,        MVT::v4f16, Custom);
2207       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f16, Custom);
2208       // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2209       setOperationAction(ISD::SINT_TO_FP,        MVT::v2f16, Custom);
2210       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f16, Custom);
2211       setOperationAction(ISD::UINT_TO_FP,        MVT::v2f16, Custom);
2212       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f16, Custom);
2213       setOperationAction(ISD::SINT_TO_FP,        MVT::v4f16, Custom);
2214       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f16, Custom);
2215       setOperationAction(ISD::UINT_TO_FP,        MVT::v4f16, Custom);
2216       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f16, Custom);
2217       // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2218       setOperationAction(ISD::FP_ROUND,          MVT::v2f16, Custom);
2219       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v2f16, Custom);
2220       setOperationAction(ISD::FP_ROUND,          MVT::v4f16, Custom);
2221       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v4f16, Custom);
2222       // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2223       setOperationAction(ISD::FP_EXTEND,         MVT::v2f16, Custom);
2224       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v2f16, Custom);
2225       setOperationAction(ISD::FP_EXTEND,         MVT::v4f16, Custom);
2226       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v4f16, Custom);
2227     }
2228 
2229     setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
2230     setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
2231     setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
2232   }
2233 
2234   if (Subtarget.hasAMXTILE()) {
2235     addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2236   }
2237 
2238   // We want to custom lower some of our intrinsics.
2239   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
2240   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
2241   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
2242   if (!Subtarget.is64Bit()) {
2243     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
2244   }
2245 
2246   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2247   // handle type legalization for these operations here.
2248   //
2249   // FIXME: We really should do custom legalization for addition and
2250   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
2251   // than generic legalization for 64-bit multiplication-with-overflow, though.
2252   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2253     if (VT == MVT::i64 && !Subtarget.is64Bit())
2254       continue;
2255     // Add/Sub/Mul with overflow operations are custom lowered.
2256     setOperationAction(ISD::SADDO, VT, Custom);
2257     setOperationAction(ISD::UADDO, VT, Custom);
2258     setOperationAction(ISD::SSUBO, VT, Custom);
2259     setOperationAction(ISD::USUBO, VT, Custom);
2260     setOperationAction(ISD::SMULO, VT, Custom);
2261     setOperationAction(ISD::UMULO, VT, Custom);
2262 
2263     // Support carry in as value rather than glue.
2264     setOperationAction(ISD::ADDCARRY, VT, Custom);
2265     setOperationAction(ISD::SUBCARRY, VT, Custom);
2266     setOperationAction(ISD::SETCCCARRY, VT, Custom);
2267     setOperationAction(ISD::SADDO_CARRY, VT, Custom);
2268     setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
2269   }
2270 
2271   if (!Subtarget.is64Bit()) {
2272     // These libcalls are not available in 32-bit.
2273     setLibcallName(RTLIB::SHL_I128, nullptr);
2274     setLibcallName(RTLIB::SRL_I128, nullptr);
2275     setLibcallName(RTLIB::SRA_I128, nullptr);
2276     setLibcallName(RTLIB::MUL_I128, nullptr);
2277     // The MULO libcall is not part of libgcc, only compiler-rt.
2278     setLibcallName(RTLIB::MULO_I64, nullptr);
2279   }
2280   // The MULO libcall is not part of libgcc, only compiler-rt.
2281   setLibcallName(RTLIB::MULO_I128, nullptr);
2282 
2283   // Combine sin / cos into _sincos_stret if it is available.
2284   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
2285       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
2286     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
2287     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
2288   }
2289 
2290   if (Subtarget.isTargetWin64()) {
2291     setOperationAction(ISD::SDIV, MVT::i128, Custom);
2292     setOperationAction(ISD::UDIV, MVT::i128, Custom);
2293     setOperationAction(ISD::SREM, MVT::i128, Custom);
2294     setOperationAction(ISD::UREM, MVT::i128, Custom);
2295     setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
2296     setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
2297     setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
2298     setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
2299     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
2300     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
2301     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
2302     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
2303   }
2304 
2305   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2306   // is. We should promote the value to 64-bits to solve this.
2307   // This is what the CRT headers do - `fmodf` is an inline header
2308   // function casting to f64 and calling `fmod`.
2309   if (Subtarget.is32Bit() &&
2310       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2311     for (ISD::NodeType Op :
2312          {ISD::FCEIL,  ISD::STRICT_FCEIL,
2313           ISD::FCOS,   ISD::STRICT_FCOS,
2314           ISD::FEXP,   ISD::STRICT_FEXP,
2315           ISD::FFLOOR, ISD::STRICT_FFLOOR,
2316           ISD::FREM,   ISD::STRICT_FREM,
2317           ISD::FLOG,   ISD::STRICT_FLOG,
2318           ISD::FLOG10, ISD::STRICT_FLOG10,
2319           ISD::FPOW,   ISD::STRICT_FPOW,
2320           ISD::FSIN,   ISD::STRICT_FSIN})
2321       if (isOperationExpand(Op, MVT::f32))
2322         setOperationAction(Op, MVT::f32, Promote);
2323 
2324   // We have target-specific dag combine patterns for the following nodes:
2325   setTargetDAGCombine({ISD::VECTOR_SHUFFLE,
2326                        ISD::SCALAR_TO_VECTOR,
2327                        ISD::INSERT_VECTOR_ELT,
2328                        ISD::EXTRACT_VECTOR_ELT,
2329                        ISD::CONCAT_VECTORS,
2330                        ISD::INSERT_SUBVECTOR,
2331                        ISD::EXTRACT_SUBVECTOR,
2332                        ISD::BITCAST,
2333                        ISD::VSELECT,
2334                        ISD::SELECT,
2335                        ISD::SHL,
2336                        ISD::SRA,
2337                        ISD::SRL,
2338                        ISD::OR,
2339                        ISD::AND,
2340                        ISD::ADD,
2341                        ISD::FADD,
2342                        ISD::FSUB,
2343                        ISD::FNEG,
2344                        ISD::FMA,
2345                        ISD::STRICT_FMA,
2346                        ISD::FMINNUM,
2347                        ISD::FMAXNUM,
2348                        ISD::SUB,
2349                        ISD::LOAD,
2350                        ISD::MLOAD,
2351                        ISD::STORE,
2352                        ISD::MSTORE,
2353                        ISD::TRUNCATE,
2354                        ISD::ZERO_EXTEND,
2355                        ISD::ANY_EXTEND,
2356                        ISD::SIGN_EXTEND,
2357                        ISD::SIGN_EXTEND_INREG,
2358                        ISD::ANY_EXTEND_VECTOR_INREG,
2359                        ISD::SIGN_EXTEND_VECTOR_INREG,
2360                        ISD::ZERO_EXTEND_VECTOR_INREG,
2361                        ISD::SINT_TO_FP,
2362                        ISD::UINT_TO_FP,
2363                        ISD::STRICT_SINT_TO_FP,
2364                        ISD::STRICT_UINT_TO_FP,
2365                        ISD::SETCC,
2366                        ISD::MUL,
2367                        ISD::XOR,
2368                        ISD::MSCATTER,
2369                        ISD::MGATHER,
2370                        ISD::FP16_TO_FP,
2371                        ISD::FP_EXTEND,
2372                        ISD::STRICT_FP_EXTEND,
2373                        ISD::FP_ROUND,
2374                        ISD::STRICT_FP_ROUND});
2375 
2376   computeRegisterProperties(Subtarget.getRegisterInfo());
2377 
2378   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2379   MaxStoresPerMemsetOptSize = 8;
2380   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2381   MaxStoresPerMemcpyOptSize = 4;
2382   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2383   MaxStoresPerMemmoveOptSize = 4;
2384 
2385   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2386   // that needs to benchmarked and balanced with the potential use of vector
2387   // load/store types (PR33329, PR33914).
2388   MaxLoadsPerMemcmp = 2;
2389   MaxLoadsPerMemcmpOptSize = 2;
2390 
2391   // Default loop alignment, which can be overridden by -align-loops.
2392   setPrefLoopAlignment(Align(16));
2393 
2394   // An out-of-order CPU can speculatively execute past a predictable branch,
2395   // but a conditional move could be stalled by an expensive earlier operation.
2396   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2397   EnableExtLdPromotion = true;
2398   setPrefFunctionAlignment(Align(16));
2399 
2400   verifyIntrinsicTables();
2401 
2402   // Default to having -disable-strictnode-mutation on
2403   IsStrictFPEnabled = true;
2404 }
2405 
2406 // This has so far only been implemented for 64-bit MachO.
2407 bool X86TargetLowering::useLoadStackGuardNode() const {
2408   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2409 }
2410 
2411 bool X86TargetLowering::useStackGuardXorFP() const {
2412   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2413   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2414 }
2415 
2416 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2417                                                const SDLoc &DL) const {
2418   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2419   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2420   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2421   return SDValue(Node, 0);
2422 }
2423 
2424 TargetLoweringBase::LegalizeTypeAction
2425 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2426   if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2427       !Subtarget.hasBWI())
2428     return TypeSplitVector;
2429 
2430   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2431       !Subtarget.hasF16C() && VT.getVectorElementType() == MVT::f16)
2432     return TypeSplitVector;
2433 
2434   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2435       VT.getVectorElementType() != MVT::i1)
2436     return TypeWidenVector;
2437 
2438   return TargetLoweringBase::getPreferredVectorAction(VT);
2439 }
2440 
2441 static std::pair<MVT, unsigned>
2442 handleMaskRegisterForCallingConv(unsigned NumElts, CallingConv::ID CC,
2443                                  const X86Subtarget &Subtarget) {
2444   // v2i1/v4i1/v8i1/v16i1 all pass in xmm registers unless the calling
2445   // convention is one that uses k registers.
2446   if (NumElts == 2)
2447     return {MVT::v2i64, 1};
2448   if (NumElts == 4)
2449     return {MVT::v4i32, 1};
2450   if (NumElts == 8 && CC != CallingConv::X86_RegCall &&
2451       CC != CallingConv::Intel_OCL_BI)
2452     return {MVT::v8i16, 1};
2453   if (NumElts == 16 && CC != CallingConv::X86_RegCall &&
2454       CC != CallingConv::Intel_OCL_BI)
2455     return {MVT::v16i8, 1};
2456   // v32i1 passes in ymm unless we have BWI and the calling convention is
2457   // regcall.
2458   if (NumElts == 32 && (!Subtarget.hasBWI() || CC != CallingConv::X86_RegCall))
2459     return {MVT::v32i8, 1};
2460   // Split v64i1 vectors if we don't have v64i8 available.
2461   if (NumElts == 64 && Subtarget.hasBWI() && CC != CallingConv::X86_RegCall) {
2462     if (Subtarget.useAVX512Regs())
2463       return {MVT::v64i8, 1};
2464     return {MVT::v32i8, 2};
2465   }
2466 
2467   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2468   if (!isPowerOf2_32(NumElts) || (NumElts == 64 && !Subtarget.hasBWI()) ||
2469       NumElts > 64)
2470     return {MVT::i8, NumElts};
2471 
2472   return {MVT::INVALID_SIMPLE_VALUE_TYPE, 0};
2473 }
2474 
2475 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2476                                                      CallingConv::ID CC,
2477                                                      EVT VT) const {
2478   if (VT.isVector()) {
2479     if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512()) {
2480       unsigned NumElts = VT.getVectorNumElements();
2481 
2482       MVT RegisterVT;
2483       unsigned NumRegisters;
2484       std::tie(RegisterVT, NumRegisters) =
2485           handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2486       if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2487         return RegisterVT;
2488     }
2489 
2490     if (VT.getVectorElementType() == MVT::f16 && VT.getVectorNumElements() < 8)
2491       return MVT::v8f16;
2492   }
2493 
2494   // We will use more GPRs for f64 and f80 on 32 bits when x87 is disabled.
2495   if ((VT == MVT::f64 || VT == MVT::f80) && !Subtarget.is64Bit() &&
2496       !Subtarget.hasX87())
2497     return MVT::i32;
2498 
2499   if (VT.isVector() && VT.getVectorElementType() == MVT::bf16)
2500     return getRegisterTypeForCallingConv(Context, CC,
2501                                          VT.changeVectorElementTypeToInteger());
2502 
2503   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2504 }
2505 
2506 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2507                                                           CallingConv::ID CC,
2508                                                           EVT VT) const {
2509   if (VT.isVector()) {
2510     if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512()) {
2511       unsigned NumElts = VT.getVectorNumElements();
2512 
2513       MVT RegisterVT;
2514       unsigned NumRegisters;
2515       std::tie(RegisterVT, NumRegisters) =
2516           handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2517       if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2518         return NumRegisters;
2519     }
2520 
2521     if (VT.getVectorElementType() == MVT::f16 && VT.getVectorNumElements() < 8)
2522       return 1;
2523   }
2524 
2525   // We have to split f64 to 2 registers and f80 to 3 registers on 32 bits if
2526   // x87 is disabled.
2527   if (!Subtarget.is64Bit() && !Subtarget.hasX87()) {
2528     if (VT == MVT::f64)
2529       return 2;
2530     if (VT == MVT::f80)
2531       return 3;
2532   }
2533 
2534   if (VT.isVector() && VT.getVectorElementType() == MVT::bf16)
2535     return getNumRegistersForCallingConv(Context, CC,
2536                                          VT.changeVectorElementTypeToInteger());
2537 
2538   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2539 }
2540 
2541 unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2542     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2543     unsigned &NumIntermediates, MVT &RegisterVT) const {
2544   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2545   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2546       Subtarget.hasAVX512() &&
2547       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2548        (VT.getVectorNumElements() == 64 && !Subtarget.hasBWI()) ||
2549        VT.getVectorNumElements() > 64)) {
2550     RegisterVT = MVT::i8;
2551     IntermediateVT = MVT::i1;
2552     NumIntermediates = VT.getVectorNumElements();
2553     return NumIntermediates;
2554   }
2555 
2556   // Split v64i1 vectors if we don't have v64i8 available.
2557   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2558       CC != CallingConv::X86_RegCall) {
2559     RegisterVT = MVT::v32i8;
2560     IntermediateVT = MVT::v32i1;
2561     NumIntermediates = 2;
2562     return 2;
2563   }
2564 
2565   return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2566                                               NumIntermediates, RegisterVT);
2567 }
2568 
2569 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2570                                           LLVMContext& Context,
2571                                           EVT VT) const {
2572   if (!VT.isVector())
2573     return MVT::i8;
2574 
2575   if (Subtarget.hasAVX512()) {
2576     // Figure out what this type will be legalized to.
2577     EVT LegalVT = VT;
2578     while (getTypeAction(Context, LegalVT) != TypeLegal)
2579       LegalVT = getTypeToTransformTo(Context, LegalVT);
2580 
2581     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2582     if (LegalVT.getSimpleVT().is512BitVector())
2583       return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2584 
2585     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2586       // If we legalized to less than a 512-bit vector, then we will use a vXi1
2587       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2588       // vXi16/vXi8.
2589       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2590       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2591         return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2592     }
2593   }
2594 
2595   return VT.changeVectorElementTypeToInteger();
2596 }
2597 
2598 /// Helper for getByValTypeAlignment to determine
2599 /// the desired ByVal argument alignment.
2600 static void getMaxByValAlign(Type *Ty, Align &MaxAlign) {
2601   if (MaxAlign == 16)
2602     return;
2603   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2604     if (VTy->getPrimitiveSizeInBits().getFixedSize() == 128)
2605       MaxAlign = Align(16);
2606   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2607     Align EltAlign;
2608     getMaxByValAlign(ATy->getElementType(), EltAlign);
2609     if (EltAlign > MaxAlign)
2610       MaxAlign = EltAlign;
2611   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2612     for (auto *EltTy : STy->elements()) {
2613       Align EltAlign;
2614       getMaxByValAlign(EltTy, EltAlign);
2615       if (EltAlign > MaxAlign)
2616         MaxAlign = EltAlign;
2617       if (MaxAlign == 16)
2618         break;
2619     }
2620   }
2621 }
2622 
2623 /// Return the desired alignment for ByVal aggregate
2624 /// function arguments in the caller parameter area. For X86, aggregates
2625 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2626 /// are at 4-byte boundaries.
2627 uint64_t X86TargetLowering::getByValTypeAlignment(Type *Ty,
2628                                                   const DataLayout &DL) const {
2629   if (Subtarget.is64Bit()) {
2630     // Max of 8 and alignment of type.
2631     Align TyAlign = DL.getABITypeAlign(Ty);
2632     if (TyAlign > 8)
2633       return TyAlign.value();
2634     return 8;
2635   }
2636 
2637   Align Alignment(4);
2638   if (Subtarget.hasSSE1())
2639     getMaxByValAlign(Ty, Alignment);
2640   return Alignment.value();
2641 }
2642 
2643 /// It returns EVT::Other if the type should be determined using generic
2644 /// target-independent logic.
2645 /// For vector ops we check that the overall size isn't larger than our
2646 /// preferred vector width.
2647 EVT X86TargetLowering::getOptimalMemOpType(
2648     const MemOp &Op, const AttributeList &FuncAttributes) const {
2649   if (!FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
2650     if (Op.size() >= 16 &&
2651         (!Subtarget.isUnalignedMem16Slow() || Op.isAligned(Align(16)))) {
2652       // FIXME: Check if unaligned 64-byte accesses are slow.
2653       if (Op.size() >= 64 && Subtarget.hasAVX512() &&
2654           (Subtarget.getPreferVectorWidth() >= 512)) {
2655         return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2656       }
2657       // FIXME: Check if unaligned 32-byte accesses are slow.
2658       if (Op.size() >= 32 && Subtarget.hasAVX() &&
2659           (Subtarget.getPreferVectorWidth() >= 256)) {
2660         // Although this isn't a well-supported type for AVX1, we'll let
2661         // legalization and shuffle lowering produce the optimal codegen. If we
2662         // choose an optimal type with a vector element larger than a byte,
2663         // getMemsetStores() may create an intermediate splat (using an integer
2664         // multiply) before we splat as a vector.
2665         return MVT::v32i8;
2666       }
2667       if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2668         return MVT::v16i8;
2669       // TODO: Can SSE1 handle a byte vector?
2670       // If we have SSE1 registers we should be able to use them.
2671       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2672           (Subtarget.getPreferVectorWidth() >= 128))
2673         return MVT::v4f32;
2674     } else if (((Op.isMemcpy() && !Op.isMemcpyStrSrc()) || Op.isZeroMemset()) &&
2675                Op.size() >= 8 && !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2676       // Do not use f64 to lower memcpy if source is string constant. It's
2677       // better to use i32 to avoid the loads.
2678       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2679       // The gymnastics of splatting a byte value into an XMM register and then
2680       // only using 8-byte stores (because this is a CPU with slow unaligned
2681       // 16-byte accesses) makes that a loser.
2682       return MVT::f64;
2683     }
2684   }
2685   // This is a compromise. If we reach here, unaligned accesses may be slow on
2686   // this target. However, creating smaller, aligned accesses could be even
2687   // slower and would certainly be a lot more code.
2688   if (Subtarget.is64Bit() && Op.size() >= 8)
2689     return MVT::i64;
2690   return MVT::i32;
2691 }
2692 
2693 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2694   if (VT == MVT::f32)
2695     return Subtarget.hasSSE1();
2696   if (VT == MVT::f64)
2697     return Subtarget.hasSSE2();
2698   return true;
2699 }
2700 
2701 bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2702     EVT VT, unsigned, Align Alignment, MachineMemOperand::Flags Flags,
2703     bool *Fast) const {
2704   if (Fast) {
2705     switch (VT.getSizeInBits()) {
2706     default:
2707       // 8-byte and under are always assumed to be fast.
2708       *Fast = true;
2709       break;
2710     case 128:
2711       *Fast = !Subtarget.isUnalignedMem16Slow();
2712       break;
2713     case 256:
2714       *Fast = !Subtarget.isUnalignedMem32Slow();
2715       break;
2716     // TODO: What about AVX-512 (512-bit) accesses?
2717     }
2718   }
2719   // NonTemporal vector memory ops must be aligned.
2720   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2721     // NT loads can only be vector aligned, so if its less aligned than the
2722     // minimum vector size (which we can split the vector down to), we might as
2723     // well use a regular unaligned vector load.
2724     // We don't have any NT loads pre-SSE41.
2725     if (!!(Flags & MachineMemOperand::MOLoad))
2726       return (Alignment < 16 || !Subtarget.hasSSE41());
2727     return false;
2728   }
2729   // Misaligned accesses of any size are always allowed.
2730   return true;
2731 }
2732 
2733 /// Return the entry encoding for a jump table in the
2734 /// current function.  The returned value is a member of the
2735 /// MachineJumpTableInfo::JTEntryKind enum.
2736 unsigned X86TargetLowering::getJumpTableEncoding() const {
2737   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2738   // symbol.
2739   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2740     return MachineJumpTableInfo::EK_Custom32;
2741 
2742   // Otherwise, use the normal jump table encoding heuristics.
2743   return TargetLowering::getJumpTableEncoding();
2744 }
2745 
2746 bool X86TargetLowering::splitValueIntoRegisterParts(
2747     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2748     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
2749   bool IsABIRegCopy = CC.has_value();
2750   EVT ValueVT = Val.getValueType();
2751   if (IsABIRegCopy && ValueVT == MVT::bf16 && PartVT == MVT::f32) {
2752     unsigned ValueBits = ValueVT.getSizeInBits();
2753     unsigned PartBits = PartVT.getSizeInBits();
2754     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
2755     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
2756     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
2757     Parts[0] = Val;
2758     return true;
2759   }
2760   return false;
2761 }
2762 
2763 SDValue X86TargetLowering::joinRegisterPartsIntoValue(
2764     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2765     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
2766   bool IsABIRegCopy = CC.has_value();
2767   if (IsABIRegCopy && ValueVT == MVT::bf16 && PartVT == MVT::f32) {
2768     unsigned ValueBits = ValueVT.getSizeInBits();
2769     unsigned PartBits = PartVT.getSizeInBits();
2770     SDValue Val = Parts[0];
2771 
2772     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
2773     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
2774     Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
2775     return Val;
2776   }
2777   return SDValue();
2778 }
2779 
2780 bool X86TargetLowering::useSoftFloat() const {
2781   return Subtarget.useSoftFloat();
2782 }
2783 
2784 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2785                                               ArgListTy &Args) const {
2786 
2787   // Only relabel X86-32 for C / Stdcall CCs.
2788   if (Subtarget.is64Bit())
2789     return;
2790   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2791     return;
2792   unsigned ParamRegs = 0;
2793   if (auto *M = MF->getFunction().getParent())
2794     ParamRegs = M->getNumberRegisterParameters();
2795 
2796   // Mark the first N int arguments as having reg
2797   for (auto &Arg : Args) {
2798     Type *T = Arg.Ty;
2799     if (T->isIntOrPtrTy())
2800       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2801         unsigned numRegs = 1;
2802         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2803           numRegs = 2;
2804         if (ParamRegs < numRegs)
2805           return;
2806         ParamRegs -= numRegs;
2807         Arg.IsInReg = true;
2808       }
2809   }
2810 }
2811 
2812 const MCExpr *
2813 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2814                                              const MachineBasicBlock *MBB,
2815                                              unsigned uid,MCContext &Ctx) const{
2816   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2817   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2818   // entries.
2819   return MCSymbolRefExpr::create(MBB->getSymbol(),
2820                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2821 }
2822 
2823 /// Returns relocation base for the given PIC jumptable.
2824 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2825                                                     SelectionDAG &DAG) const {
2826   if (!Subtarget.is64Bit())
2827     // This doesn't have SDLoc associated with it, but is not really the
2828     // same as a Register.
2829     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2830                        getPointerTy(DAG.getDataLayout()));
2831   return Table;
2832 }
2833 
2834 /// This returns the relocation base for the given PIC jumptable,
2835 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2836 const MCExpr *X86TargetLowering::
2837 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2838                              MCContext &Ctx) const {
2839   // X86-64 uses RIP relative addressing based on the jump table label.
2840   if (Subtarget.isPICStyleRIPRel())
2841     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2842 
2843   // Otherwise, the reference is relative to the PIC base.
2844   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2845 }
2846 
2847 std::pair<const TargetRegisterClass *, uint8_t>
2848 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2849                                            MVT VT) const {
2850   const TargetRegisterClass *RRC = nullptr;
2851   uint8_t Cost = 1;
2852   switch (VT.SimpleTy) {
2853   default:
2854     return TargetLowering::findRepresentativeClass(TRI, VT);
2855   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2856     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2857     break;
2858   case MVT::x86mmx:
2859     RRC = &X86::VR64RegClass;
2860     break;
2861   case MVT::f32: case MVT::f64:
2862   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2863   case MVT::v4f32: case MVT::v2f64:
2864   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2865   case MVT::v8f32: case MVT::v4f64:
2866   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2867   case MVT::v16f32: case MVT::v8f64:
2868     RRC = &X86::VR128XRegClass;
2869     break;
2870   }
2871   return std::make_pair(RRC, Cost);
2872 }
2873 
2874 unsigned X86TargetLowering::getAddressSpace() const {
2875   if (Subtarget.is64Bit())
2876     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2877   return 256;
2878 }
2879 
2880 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2881   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2882          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2883 }
2884 
2885 static Constant* SegmentOffset(IRBuilderBase &IRB,
2886                                int Offset, unsigned AddressSpace) {
2887   return ConstantExpr::getIntToPtr(
2888       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2889       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2890 }
2891 
2892 Value *X86TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
2893   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2894   // tcbhead_t; use it instead of the usual global variable (see
2895   // sysdeps/{i386,x86_64}/nptl/tls.h)
2896   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2897     if (Subtarget.isTargetFuchsia()) {
2898       // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2899       return SegmentOffset(IRB, 0x10, getAddressSpace());
2900     } else {
2901       unsigned AddressSpace = getAddressSpace();
2902       Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2903       // Specially, some users may customize the base reg and offset.
2904       int Offset = M->getStackProtectorGuardOffset();
2905       // If we don't set -stack-protector-guard-offset value:
2906       // %fs:0x28, unless we're using a Kernel code model, in which case
2907       // it's %gs:0x28.  gs:0x14 on i386.
2908       if (Offset == INT_MAX)
2909         Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2910 
2911       StringRef GuardReg = M->getStackProtectorGuardReg();
2912       if (GuardReg == "fs")
2913         AddressSpace = X86AS::FS;
2914       else if (GuardReg == "gs")
2915         AddressSpace = X86AS::GS;
2916 
2917       // Use symbol guard if user specify.
2918       StringRef GuardSymb = M->getStackProtectorGuardSymbol();
2919       if (!GuardSymb.empty()) {
2920         GlobalVariable *GV = M->getGlobalVariable(GuardSymb);
2921         if (!GV) {
2922           Type *Ty = Subtarget.is64Bit() ? Type::getInt64Ty(M->getContext())
2923                                          : Type::getInt32Ty(M->getContext());
2924           GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
2925                                   nullptr, GuardSymb, nullptr,
2926                                   GlobalValue::NotThreadLocal, AddressSpace);
2927         }
2928         return GV;
2929       }
2930 
2931       return SegmentOffset(IRB, Offset, AddressSpace);
2932     }
2933   }
2934   return TargetLowering::getIRStackGuard(IRB);
2935 }
2936 
2937 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2938   // MSVC CRT provides functionalities for stack protection.
2939   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2940       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2941     // MSVC CRT has a global variable holding security cookie.
2942     M.getOrInsertGlobal("__security_cookie",
2943                         Type::getInt8PtrTy(M.getContext()));
2944 
2945     // MSVC CRT has a function to validate security cookie.
2946     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2947         "__security_check_cookie", Type::getVoidTy(M.getContext()),
2948         Type::getInt8PtrTy(M.getContext()));
2949     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2950       F->setCallingConv(CallingConv::X86_FastCall);
2951       F->addParamAttr(0, Attribute::AttrKind::InReg);
2952     }
2953     return;
2954   }
2955 
2956   StringRef GuardMode = M.getStackProtectorGuard();
2957 
2958   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2959   if ((GuardMode == "tls" || GuardMode.empty()) &&
2960       hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2961     return;
2962   TargetLowering::insertSSPDeclarations(M);
2963 }
2964 
2965 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2966   // MSVC CRT has a global variable holding security cookie.
2967   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2968       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2969     return M.getGlobalVariable("__security_cookie");
2970   }
2971   return TargetLowering::getSDagStackGuard(M);
2972 }
2973 
2974 Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2975   // MSVC CRT has a function to validate security cookie.
2976   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2977       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2978     return M.getFunction("__security_check_cookie");
2979   }
2980   return TargetLowering::getSSPStackGuardCheck(M);
2981 }
2982 
2983 Value *
2984 X86TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
2985   if (Subtarget.getTargetTriple().isOSContiki())
2986     return getDefaultSafeStackPointerLocation(IRB, false);
2987 
2988   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2989   // definition of TLS_SLOT_SAFESTACK in
2990   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2991   if (Subtarget.isTargetAndroid()) {
2992     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2993     // %gs:0x24 on i386
2994     int Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2995     return SegmentOffset(IRB, Offset, getAddressSpace());
2996   }
2997 
2998   // Fuchsia is similar.
2999   if (Subtarget.isTargetFuchsia()) {
3000     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
3001     return SegmentOffset(IRB, 0x18, getAddressSpace());
3002   }
3003 
3004   return TargetLowering::getSafeStackPointerLocation(IRB);
3005 }
3006 
3007 //===----------------------------------------------------------------------===//
3008 //               Return Value Calling Convention Implementation
3009 //===----------------------------------------------------------------------===//
3010 
3011 bool X86TargetLowering::CanLowerReturn(
3012     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3013     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3014   SmallVector<CCValAssign, 16> RVLocs;
3015   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3016   return CCInfo.CheckReturn(Outs, RetCC_X86);
3017 }
3018 
3019 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
3020   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
3021   return ScratchRegs;
3022 }
3023 
3024 /// Lowers masks values (v*i1) to the local register values
3025 /// \returns DAG node after lowering to register type
3026 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
3027                                const SDLoc &Dl, SelectionDAG &DAG) {
3028   EVT ValVT = ValArg.getValueType();
3029 
3030   if (ValVT == MVT::v1i1)
3031     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
3032                        DAG.getIntPtrConstant(0, Dl));
3033 
3034   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
3035       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
3036     // Two stage lowering might be required
3037     // bitcast:   v8i1 -> i8 / v16i1 -> i16
3038     // anyextend: i8   -> i32 / i16   -> i32
3039     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
3040     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
3041     if (ValLoc == MVT::i32)
3042       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
3043     return ValToCopy;
3044   }
3045 
3046   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
3047       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
3048     // One stage lowering is required
3049     // bitcast:   v32i1 -> i32 / v64i1 -> i64
3050     return DAG.getBitcast(ValLoc, ValArg);
3051   }
3052 
3053   return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
3054 }
3055 
3056 /// Breaks v64i1 value into two registers and adds the new node to the DAG
3057 static void Passv64i1ArgInRegs(
3058     const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
3059     SmallVectorImpl<std::pair<Register, SDValue>> &RegsToPass, CCValAssign &VA,
3060     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
3061   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
3062   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
3063   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
3064   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
3065          "The value should reside in two registers");
3066 
3067   // Before splitting the value we cast it to i64
3068   Arg = DAG.getBitcast(MVT::i64, Arg);
3069 
3070   // Splitting the value into two i32 types
3071   SDValue Lo, Hi;
3072   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
3073                    DAG.getConstant(0, Dl, MVT::i32));
3074   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
3075                    DAG.getConstant(1, Dl, MVT::i32));
3076 
3077   // Attach the two i32 types into corresponding registers
3078   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
3079   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
3080 }
3081 
3082 SDValue
3083 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3084                                bool isVarArg,
3085                                const SmallVectorImpl<ISD::OutputArg> &Outs,
3086                                const SmallVectorImpl<SDValue> &OutVals,
3087                                const SDLoc &dl, SelectionDAG &DAG) const {
3088   MachineFunction &MF = DAG.getMachineFunction();
3089   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3090 
3091   // In some cases we need to disable registers from the default CSR list.
3092   // For example, when they are used for argument passing.
3093   bool ShouldDisableCalleeSavedRegister =
3094       CallConv == CallingConv::X86_RegCall ||
3095       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
3096 
3097   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
3098     report_fatal_error("X86 interrupts may not return any value");
3099 
3100   SmallVector<CCValAssign, 16> RVLocs;
3101   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
3102   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
3103 
3104   SmallVector<std::pair<Register, SDValue>, 4> RetVals;
3105   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
3106        ++I, ++OutsIndex) {
3107     CCValAssign &VA = RVLocs[I];
3108     assert(VA.isRegLoc() && "Can only return in registers!");
3109 
3110     // Add the register to the CalleeSaveDisableRegs list.
3111     if (ShouldDisableCalleeSavedRegister)
3112       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
3113 
3114     SDValue ValToCopy = OutVals[OutsIndex];
3115     EVT ValVT = ValToCopy.getValueType();
3116 
3117     // Promote values to the appropriate types.
3118     if (VA.getLocInfo() == CCValAssign::SExt)
3119       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
3120     else if (VA.getLocInfo() == CCValAssign::ZExt)
3121       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
3122     else if (VA.getLocInfo() == CCValAssign::AExt) {
3123       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
3124         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
3125       else
3126         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
3127     }
3128     else if (VA.getLocInfo() == CCValAssign::BCvt)
3129       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
3130 
3131     assert(VA.getLocInfo() != CCValAssign::FPExt &&
3132            "Unexpected FP-extend for return value.");
3133 
3134     // Report an error if we have attempted to return a value via an XMM
3135     // register and SSE was disabled.
3136     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3137       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3138       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3139     } else if (!Subtarget.hasSSE2() &&
3140                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3141                ValVT == MVT::f64) {
3142       // When returning a double via an XMM register, report an error if SSE2 is
3143       // not enabled.
3144       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3145       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3146     }
3147 
3148     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
3149     // the RET instruction and handled by the FP Stackifier.
3150     if (VA.getLocReg() == X86::FP0 ||
3151         VA.getLocReg() == X86::FP1) {
3152       // If this is a copy from an xmm register to ST(0), use an FPExtend to
3153       // change the value to the FP stack register class.
3154       if (isScalarFPTypeInSSEReg(VA.getValVT()))
3155         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
3156       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
3157       // Don't emit a copytoreg.
3158       continue;
3159     }
3160 
3161     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
3162     // which is returned in RAX / RDX.
3163     if (Subtarget.is64Bit()) {
3164       if (ValVT == MVT::x86mmx) {
3165         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
3166           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
3167           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
3168                                   ValToCopy);
3169           // If we don't have SSE2 available, convert to v4f32 so the generated
3170           // register is legal.
3171           if (!Subtarget.hasSSE2())
3172             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
3173         }
3174       }
3175     }
3176 
3177     if (VA.needsCustom()) {
3178       assert(VA.getValVT() == MVT::v64i1 &&
3179              "Currently the only custom case is when we split v64i1 to 2 regs");
3180 
3181       Passv64i1ArgInRegs(dl, DAG, ValToCopy, RetVals, VA, RVLocs[++I],
3182                          Subtarget);
3183 
3184       // Add the second register to the CalleeSaveDisableRegs list.
3185       if (ShouldDisableCalleeSavedRegister)
3186         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
3187     } else {
3188       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
3189     }
3190   }
3191 
3192   SDValue Flag;
3193   SmallVector<SDValue, 6> RetOps;
3194   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3195   // Operand #1 = Bytes To Pop
3196   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
3197                    MVT::i32));
3198 
3199   // Copy the result values into the output registers.
3200   for (auto &RetVal : RetVals) {
3201     if (RetVal.first == X86::FP0 || RetVal.first == X86::FP1) {
3202       RetOps.push_back(RetVal.second);
3203       continue; // Don't emit a copytoreg.
3204     }
3205 
3206     Chain = DAG.getCopyToReg(Chain, dl, RetVal.first, RetVal.second, Flag);
3207     Flag = Chain.getValue(1);
3208     RetOps.push_back(
3209         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
3210   }
3211 
3212   // Swift calling convention does not require we copy the sret argument
3213   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
3214 
3215   // All x86 ABIs require that for returning structs by value we copy
3216   // the sret argument into %rax/%eax (depending on ABI) for the return.
3217   // We saved the argument into a virtual register in the entry block,
3218   // so now we copy the value out and into %rax/%eax.
3219   //
3220   // Checking Function.hasStructRetAttr() here is insufficient because the IR
3221   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
3222   // false, then an sret argument may be implicitly inserted in the SelDAG. In
3223   // either case FuncInfo->setSRetReturnReg() will have been called.
3224   if (Register SRetReg = FuncInfo->getSRetReturnReg()) {
3225     // When we have both sret and another return value, we should use the
3226     // original Chain stored in RetOps[0], instead of the current Chain updated
3227     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
3228 
3229     // For the case of sret and another return value, we have
3230     //   Chain_0 at the function entry
3231     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
3232     // If we use Chain_1 in getCopyFromReg, we will have
3233     //   Val = getCopyFromReg(Chain_1)
3234     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
3235 
3236     // getCopyToReg(Chain_0) will be glued together with
3237     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
3238     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
3239     //   Data dependency from Unit B to Unit A due to usage of Val in
3240     //     getCopyToReg(Chain_1, Val)
3241     //   Chain dependency from Unit A to Unit B
3242 
3243     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
3244     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
3245                                      getPointerTy(MF.getDataLayout()));
3246 
3247     Register RetValReg
3248         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
3249           X86::RAX : X86::EAX;
3250     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
3251     Flag = Chain.getValue(1);
3252 
3253     // RAX/EAX now acts like a return value.
3254     RetOps.push_back(
3255         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
3256 
3257     // Add the returned register to the CalleeSaveDisableRegs list.
3258     if (ShouldDisableCalleeSavedRegister)
3259       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
3260   }
3261 
3262   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
3263   const MCPhysReg *I =
3264       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3265   if (I) {
3266     for (; *I; ++I) {
3267       if (X86::GR64RegClass.contains(*I))
3268         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3269       else
3270         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3271     }
3272   }
3273 
3274   RetOps[0] = Chain;  // Update chain.
3275 
3276   // Add the flag if we have it.
3277   if (Flag.getNode())
3278     RetOps.push_back(Flag);
3279 
3280   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
3281   if (CallConv == CallingConv::X86_INTR)
3282     opcode = X86ISD::IRET;
3283   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
3284 }
3285 
3286 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3287   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
3288     return false;
3289 
3290   SDValue TCChain = Chain;
3291   SDNode *Copy = *N->use_begin();
3292   if (Copy->getOpcode() == ISD::CopyToReg) {
3293     // If the copy has a glue operand, we conservatively assume it isn't safe to
3294     // perform a tail call.
3295     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3296       return false;
3297     TCChain = Copy->getOperand(0);
3298   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
3299     return false;
3300 
3301   bool HasRet = false;
3302   for (const SDNode *U : Copy->uses()) {
3303     if (U->getOpcode() != X86ISD::RET_FLAG)
3304       return false;
3305     // If we are returning more than one value, we can definitely
3306     // not make a tail call see PR19530
3307     if (U->getNumOperands() > 4)
3308       return false;
3309     if (U->getNumOperands() == 4 &&
3310         U->getOperand(U->getNumOperands() - 1).getValueType() != MVT::Glue)
3311       return false;
3312     HasRet = true;
3313   }
3314 
3315   if (!HasRet)
3316     return false;
3317 
3318   Chain = TCChain;
3319   return true;
3320 }
3321 
3322 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
3323                                            ISD::NodeType ExtendKind) const {
3324   MVT ReturnMVT = MVT::i32;
3325 
3326   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
3327   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
3328     // The ABI does not require i1, i8 or i16 to be extended.
3329     //
3330     // On Darwin, there is code in the wild relying on Clang's old behaviour of
3331     // always extending i8/i16 return values, so keep doing that for now.
3332     // (PR26665).
3333     ReturnMVT = MVT::i8;
3334   }
3335 
3336   EVT MinVT = getRegisterType(Context, ReturnMVT);
3337   return VT.bitsLT(MinVT) ? MinVT : VT;
3338 }
3339 
3340 /// Reads two 32 bit registers and creates a 64 bit mask value.
3341 /// \param VA The current 32 bit value that need to be assigned.
3342 /// \param NextVA The next 32 bit value that need to be assigned.
3343 /// \param Root The parent DAG node.
3344 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
3345 ///                        glue purposes. In the case the DAG is already using
3346 ///                        physical register instead of virtual, we should glue
3347 ///                        our new SDValue to InFlag SDvalue.
3348 /// \return a new SDvalue of size 64bit.
3349 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
3350                                 SDValue &Root, SelectionDAG &DAG,
3351                                 const SDLoc &Dl, const X86Subtarget &Subtarget,
3352                                 SDValue *InFlag = nullptr) {
3353   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
3354   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
3355   assert(VA.getValVT() == MVT::v64i1 &&
3356          "Expecting first location of 64 bit width type");
3357   assert(NextVA.getValVT() == VA.getValVT() &&
3358          "The locations should have the same type");
3359   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
3360          "The values should reside in two registers");
3361 
3362   SDValue Lo, Hi;
3363   SDValue ArgValueLo, ArgValueHi;
3364 
3365   MachineFunction &MF = DAG.getMachineFunction();
3366   const TargetRegisterClass *RC = &X86::GR32RegClass;
3367 
3368   // Read a 32 bit value from the registers.
3369   if (nullptr == InFlag) {
3370     // When no physical register is present,
3371     // create an intermediate virtual register.
3372     Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3373     ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
3374     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3375     ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
3376   } else {
3377     // When a physical register is available read the value from it and glue
3378     // the reads together.
3379     ArgValueLo =
3380       DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
3381     *InFlag = ArgValueLo.getValue(2);
3382     ArgValueHi =
3383       DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
3384     *InFlag = ArgValueHi.getValue(2);
3385   }
3386 
3387   // Convert the i32 type into v32i1 type.
3388   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
3389 
3390   // Convert the i32 type into v32i1 type.
3391   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
3392 
3393   // Concatenate the two values together.
3394   return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
3395 }
3396 
3397 /// The function will lower a register of various sizes (8/16/32/64)
3398 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
3399 /// \returns a DAG node contains the operand after lowering to mask type.
3400 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
3401                                const EVT &ValLoc, const SDLoc &Dl,
3402                                SelectionDAG &DAG) {
3403   SDValue ValReturned = ValArg;
3404 
3405   if (ValVT == MVT::v1i1)
3406     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
3407 
3408   if (ValVT == MVT::v64i1) {
3409     // In 32 bit machine, this case is handled by getv64i1Argument
3410     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
3411     // In 64 bit machine, There is no need to truncate the value only bitcast
3412   } else {
3413     MVT maskLen;
3414     switch (ValVT.getSimpleVT().SimpleTy) {
3415     case MVT::v8i1:
3416       maskLen = MVT::i8;
3417       break;
3418     case MVT::v16i1:
3419       maskLen = MVT::i16;
3420       break;
3421     case MVT::v32i1:
3422       maskLen = MVT::i32;
3423       break;
3424     default:
3425       llvm_unreachable("Expecting a vector of i1 types");
3426     }
3427 
3428     ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
3429   }
3430   return DAG.getBitcast(ValVT, ValReturned);
3431 }
3432 
3433 /// Lower the result values of a call into the
3434 /// appropriate copies out of appropriate physical registers.
3435 ///
3436 SDValue X86TargetLowering::LowerCallResult(
3437     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3438     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3439     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3440     uint32_t *RegMask) const {
3441 
3442   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3443   // Assign locations to each value returned by this call.
3444   SmallVector<CCValAssign, 16> RVLocs;
3445   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3446                  *DAG.getContext());
3447   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3448 
3449   // Copy all of the result registers out of their specified physreg.
3450   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
3451        ++I, ++InsIndex) {
3452     CCValAssign &VA = RVLocs[I];
3453     EVT CopyVT = VA.getLocVT();
3454 
3455     // In some calling conventions we need to remove the used registers
3456     // from the register mask.
3457     if (RegMask) {
3458       for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
3459            SubRegs.isValid(); ++SubRegs)
3460         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3461     }
3462 
3463     // Report an error if there was an attempt to return FP values via XMM
3464     // registers.
3465     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3466       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3467       if (VA.getLocReg() == X86::XMM1)
3468         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3469       else
3470         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3471     } else if (!Subtarget.hasSSE2() &&
3472                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3473                CopyVT == MVT::f64) {
3474       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3475       if (VA.getLocReg() == X86::XMM1)
3476         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3477       else
3478         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3479     }
3480 
3481     // If we prefer to use the value in xmm registers, copy it out as f80 and
3482     // use a truncate to move it from fp stack reg to xmm reg.
3483     bool RoundAfterCopy = false;
3484     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3485         isScalarFPTypeInSSEReg(VA.getValVT())) {
3486       if (!Subtarget.hasX87())
3487         report_fatal_error("X87 register return with X87 disabled");
3488       CopyVT = MVT::f80;
3489       RoundAfterCopy = (CopyVT != VA.getLocVT());
3490     }
3491 
3492     SDValue Val;
3493     if (VA.needsCustom()) {
3494       assert(VA.getValVT() == MVT::v64i1 &&
3495              "Currently the only custom case is when we split v64i1 to 2 regs");
3496       Val =
3497           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
3498     } else {
3499       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
3500                   .getValue(1);
3501       Val = Chain.getValue(0);
3502       InFlag = Chain.getValue(2);
3503     }
3504 
3505     if (RoundAfterCopy)
3506       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3507                         // This truncation won't change the value.
3508                         DAG.getIntPtrConstant(1, dl));
3509 
3510     if (VA.isExtInLoc()) {
3511       if (VA.getValVT().isVector() &&
3512           VA.getValVT().getScalarType() == MVT::i1 &&
3513           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3514            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3515         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3516         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3517       } else
3518         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3519     }
3520 
3521     if (VA.getLocInfo() == CCValAssign::BCvt)
3522       Val = DAG.getBitcast(VA.getValVT(), Val);
3523 
3524     InVals.push_back(Val);
3525   }
3526 
3527   return Chain;
3528 }
3529 
3530 //===----------------------------------------------------------------------===//
3531 //                C & StdCall & Fast Calling Convention implementation
3532 //===----------------------------------------------------------------------===//
3533 //  StdCall calling convention seems to be standard for many Windows' API
3534 //  routines and around. It differs from C calling convention just a little:
3535 //  callee should clean up the stack, not caller. Symbols should be also
3536 //  decorated in some fancy way :) It doesn't support any vector arguments.
3537 //  For info on fast calling convention see Fast Calling Convention (tail call)
3538 //  implementation LowerX86_32FastCCCallTo.
3539 
3540 /// Determines whether Args, either a set of outgoing arguments to a call, or a
3541 /// set of incoming args of a call, contains an sret pointer that the callee
3542 /// pops
3543 template <typename T>
3544 static bool hasCalleePopSRet(const SmallVectorImpl<T> &Args,
3545                              const X86Subtarget &Subtarget) {
3546   // Not C++20 (yet), so no concepts available.
3547   static_assert(std::is_same<T, ISD::OutputArg>::value ||
3548                     std::is_same<T, ISD::InputArg>::value,
3549                 "requires ISD::OutputArg or ISD::InputArg");
3550 
3551   // Only 32-bit pops the sret.  It's a 64-bit world these days, so early-out
3552   // for most compilations.
3553   if (!Subtarget.is32Bit())
3554     return false;
3555 
3556   if (Args.empty())
3557     return false;
3558 
3559   // Most calls do not have an sret argument, check the arg next.
3560   const ISD::ArgFlagsTy &Flags = Args[0].Flags;
3561   if (!Flags.isSRet() || Flags.isInReg())
3562     return false;
3563 
3564   // The MSVCabi does not pop the sret.
3565   if (Subtarget.getTargetTriple().isOSMSVCRT())
3566     return false;
3567 
3568   // MCUs don't pop the sret
3569   if (Subtarget.isTargetMCU())
3570     return false;
3571 
3572   // Callee pops argument
3573   return true;
3574 }
3575 
3576 /// Make a copy of an aggregate at address specified by "Src" to address
3577 /// "Dst" with size and alignment information specified by the specific
3578 /// parameter attribute. The copy will be passed as a byval function parameter.
3579 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3580                                          SDValue Chain, ISD::ArgFlagsTy Flags,
3581                                          SelectionDAG &DAG, const SDLoc &dl) {
3582   SDValue SizeNode = DAG.getIntPtrConstant(Flags.getByValSize(), dl);
3583 
3584   return DAG.getMemcpy(
3585       Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
3586       /*isVolatile*/ false, /*AlwaysInline=*/true,
3587       /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
3588 }
3589 
3590 /// Return true if the calling convention is one that we can guarantee TCO for.
3591 static bool canGuaranteeTCO(CallingConv::ID CC) {
3592   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3593           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3594           CC == CallingConv::HHVM || CC == CallingConv::Tail ||
3595           CC == CallingConv::SwiftTail);
3596 }
3597 
3598 /// Return true if we might ever do TCO for calls with this calling convention.
3599 static bool mayTailCallThisCC(CallingConv::ID CC) {
3600   switch (CC) {
3601   // C calling conventions:
3602   case CallingConv::C:
3603   case CallingConv::Win64:
3604   case CallingConv::X86_64_SysV:
3605   // Callee pop conventions:
3606   case CallingConv::X86_ThisCall:
3607   case CallingConv::X86_StdCall:
3608   case CallingConv::X86_VectorCall:
3609   case CallingConv::X86_FastCall:
3610   // Swift:
3611   case CallingConv::Swift:
3612     return true;
3613   default:
3614     return canGuaranteeTCO(CC);
3615   }
3616 }
3617 
3618 /// Return true if the function is being made into a tailcall target by
3619 /// changing its ABI.
3620 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3621   return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) ||
3622          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
3623 }
3624 
3625 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3626   if (!CI->isTailCall())
3627     return false;
3628 
3629   CallingConv::ID CalleeCC = CI->getCallingConv();
3630   if (!mayTailCallThisCC(CalleeCC))
3631     return false;
3632 
3633   return true;
3634 }
3635 
3636 SDValue
3637 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3638                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3639                                     const SDLoc &dl, SelectionDAG &DAG,
3640                                     const CCValAssign &VA,
3641                                     MachineFrameInfo &MFI, unsigned i) const {
3642   // Create the nodes corresponding to a load from this parameter slot.
3643   ISD::ArgFlagsTy Flags = Ins[i].Flags;
3644   bool AlwaysUseMutable = shouldGuaranteeTCO(
3645       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3646   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3647   EVT ValVT;
3648   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3649 
3650   // If value is passed by pointer we have address passed instead of the value
3651   // itself. No need to extend if the mask value and location share the same
3652   // absolute size.
3653   bool ExtendedInMem =
3654       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3655       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3656 
3657   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3658     ValVT = VA.getLocVT();
3659   else
3660     ValVT = VA.getValVT();
3661 
3662   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3663   // changed with more analysis.
3664   // In case of tail call optimization mark all arguments mutable. Since they
3665   // could be overwritten by lowering of arguments in case of a tail call.
3666   if (Flags.isByVal()) {
3667     unsigned Bytes = Flags.getByValSize();
3668     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3669 
3670     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3671     // can be improved with deeper analysis.
3672     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3673                                    /*isAliased=*/true);
3674     return DAG.getFrameIndex(FI, PtrVT);
3675   }
3676 
3677   EVT ArgVT = Ins[i].ArgVT;
3678 
3679   // If this is a vector that has been split into multiple parts, and the
3680   // scalar size of the parts don't match the vector element size, then we can't
3681   // elide the copy. The parts will have padding between them instead of being
3682   // packed like a vector.
3683   bool ScalarizedAndExtendedVector =
3684       ArgVT.isVector() && !VA.getLocVT().isVector() &&
3685       VA.getLocVT().getSizeInBits() != ArgVT.getScalarSizeInBits();
3686 
3687   // This is an argument in memory. We might be able to perform copy elision.
3688   // If the argument is passed directly in memory without any extension, then we
3689   // can perform copy elision. Large vector types, for example, may be passed
3690   // indirectly by pointer.
3691   if (Flags.isCopyElisionCandidate() &&
3692       VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem &&
3693       !ScalarizedAndExtendedVector) {
3694     SDValue PartAddr;
3695     if (Ins[i].PartOffset == 0) {
3696       // If this is a one-part value or the first part of a multi-part value,
3697       // create a stack object for the entire argument value type and return a
3698       // load from our portion of it. This assumes that if the first part of an
3699       // argument is in memory, the rest will also be in memory.
3700       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3701                                      /*IsImmutable=*/false);
3702       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3703       return DAG.getLoad(
3704           ValVT, dl, Chain, PartAddr,
3705           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3706     } else {
3707       // This is not the first piece of an argument in memory. See if there is
3708       // already a fixed stack object including this offset. If so, assume it
3709       // was created by the PartOffset == 0 branch above and create a load from
3710       // the appropriate offset into it.
3711       int64_t PartBegin = VA.getLocMemOffset();
3712       int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3713       int FI = MFI.getObjectIndexBegin();
3714       for (; MFI.isFixedObjectIndex(FI); ++FI) {
3715         int64_t ObjBegin = MFI.getObjectOffset(FI);
3716         int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3717         if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3718           break;
3719       }
3720       if (MFI.isFixedObjectIndex(FI)) {
3721         SDValue Addr =
3722             DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3723                         DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3724         return DAG.getLoad(
3725             ValVT, dl, Chain, Addr,
3726             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3727                                               Ins[i].PartOffset));
3728       }
3729     }
3730   }
3731 
3732   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3733                                  VA.getLocMemOffset(), isImmutable);
3734 
3735   // Set SExt or ZExt flag.
3736   if (VA.getLocInfo() == CCValAssign::ZExt) {
3737     MFI.setObjectZExt(FI, true);
3738   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3739     MFI.setObjectSExt(FI, true);
3740   }
3741 
3742   MaybeAlign Alignment;
3743   if (Subtarget.isTargetWindowsMSVC() && !Subtarget.is64Bit() &&
3744       ValVT != MVT::f80)
3745     Alignment = MaybeAlign(4);
3746   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3747   SDValue Val = DAG.getLoad(
3748       ValVT, dl, Chain, FIN,
3749       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3750       Alignment);
3751   return ExtendedInMem
3752              ? (VA.getValVT().isVector()
3753                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3754                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3755              : Val;
3756 }
3757 
3758 // FIXME: Get this from tablegen.
3759 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3760                                                 const X86Subtarget &Subtarget) {
3761   assert(Subtarget.is64Bit());
3762 
3763   if (Subtarget.isCallingConvWin64(CallConv)) {
3764     static const MCPhysReg GPR64ArgRegsWin64[] = {
3765       X86::RCX, X86::RDX, X86::R8,  X86::R9
3766     };
3767     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3768   }
3769 
3770   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3771     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3772   };
3773   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3774 }
3775 
3776 // FIXME: Get this from tablegen.
3777 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3778                                                 CallingConv::ID CallConv,
3779                                                 const X86Subtarget &Subtarget) {
3780   assert(Subtarget.is64Bit());
3781   if (Subtarget.isCallingConvWin64(CallConv)) {
3782     // The XMM registers which might contain var arg parameters are shadowed
3783     // in their paired GPR.  So we only need to save the GPR to their home
3784     // slots.
3785     // TODO: __vectorcall will change this.
3786     return None;
3787   }
3788 
3789   bool isSoftFloat = Subtarget.useSoftFloat();
3790   if (isSoftFloat || !Subtarget.hasSSE1())
3791     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3792     // registers.
3793     return None;
3794 
3795   static const MCPhysReg XMMArgRegs64Bit[] = {
3796     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3797     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3798   };
3799   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3800 }
3801 
3802 #ifndef NDEBUG
3803 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3804   return llvm::is_sorted(
3805       ArgLocs, [](const CCValAssign &A, const CCValAssign &B) -> bool {
3806         return A.getValNo() < B.getValNo();
3807       });
3808 }
3809 #endif
3810 
3811 namespace {
3812 /// This is a helper class for lowering variable arguments parameters.
3813 class VarArgsLoweringHelper {
3814 public:
3815   VarArgsLoweringHelper(X86MachineFunctionInfo *FuncInfo, const SDLoc &Loc,
3816                         SelectionDAG &DAG, const X86Subtarget &Subtarget,
3817                         CallingConv::ID CallConv, CCState &CCInfo)
3818       : FuncInfo(FuncInfo), DL(Loc), DAG(DAG), Subtarget(Subtarget),
3819         TheMachineFunction(DAG.getMachineFunction()),
3820         TheFunction(TheMachineFunction.getFunction()),
3821         FrameInfo(TheMachineFunction.getFrameInfo()),
3822         FrameLowering(*Subtarget.getFrameLowering()),
3823         TargLowering(DAG.getTargetLoweringInfo()), CallConv(CallConv),
3824         CCInfo(CCInfo) {}
3825 
3826   // Lower variable arguments parameters.
3827   void lowerVarArgsParameters(SDValue &Chain, unsigned StackSize);
3828 
3829 private:
3830   void createVarArgAreaAndStoreRegisters(SDValue &Chain, unsigned StackSize);
3831 
3832   void forwardMustTailParameters(SDValue &Chain);
3833 
3834   bool is64Bit() const { return Subtarget.is64Bit(); }
3835   bool isWin64() const { return Subtarget.isCallingConvWin64(CallConv); }
3836 
3837   X86MachineFunctionInfo *FuncInfo;
3838   const SDLoc &DL;
3839   SelectionDAG &DAG;
3840   const X86Subtarget &Subtarget;
3841   MachineFunction &TheMachineFunction;
3842   const Function &TheFunction;
3843   MachineFrameInfo &FrameInfo;
3844   const TargetFrameLowering &FrameLowering;
3845   const TargetLowering &TargLowering;
3846   CallingConv::ID CallConv;
3847   CCState &CCInfo;
3848 };
3849 } // namespace
3850 
3851 void VarArgsLoweringHelper::createVarArgAreaAndStoreRegisters(
3852     SDValue &Chain, unsigned StackSize) {
3853   // If the function takes variable number of arguments, make a frame index for
3854   // the start of the first vararg value... for expansion of llvm.va_start. We
3855   // can skip this if there are no va_start calls.
3856   if (is64Bit() || (CallConv != CallingConv::X86_FastCall &&
3857                     CallConv != CallingConv::X86_ThisCall)) {
3858     FuncInfo->setVarArgsFrameIndex(
3859         FrameInfo.CreateFixedObject(1, StackSize, true));
3860   }
3861 
3862   // 64-bit calling conventions support varargs and register parameters, so we
3863   // have to do extra work to spill them in the prologue.
3864   if (is64Bit()) {
3865     // Find the first unallocated argument registers.
3866     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3867     ArrayRef<MCPhysReg> ArgXMMs =
3868         get64BitArgumentXMMs(TheMachineFunction, CallConv, Subtarget);
3869     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3870     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3871 
3872     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3873            "SSE register cannot be used when SSE is disabled!");
3874 
3875     if (isWin64()) {
3876       // Get to the caller-allocated home save location.  Add 8 to account
3877       // for the return address.
3878       int HomeOffset = FrameLowering.getOffsetOfLocalArea() + 8;
3879       FuncInfo->setRegSaveFrameIndex(
3880           FrameInfo.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3881       // Fixup to set vararg frame on shadow area (4 x i64).
3882       if (NumIntRegs < 4)
3883         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3884     } else {
3885       // For X86-64, if there are vararg parameters that are passed via
3886       // registers, then we must store them to their spots on the stack so
3887       // they may be loaded by dereferencing the result of va_next.
3888       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3889       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3890       FuncInfo->setRegSaveFrameIndex(FrameInfo.CreateStackObject(
3891           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, Align(16), false));
3892     }
3893 
3894     SmallVector<SDValue, 6>
3895         LiveGPRs; // list of SDValue for GPR registers keeping live input value
3896     SmallVector<SDValue, 8> LiveXMMRegs; // list of SDValue for XMM registers
3897                                          // keeping live input value
3898     SDValue ALVal; // if applicable keeps SDValue for %al register
3899 
3900     // Gather all the live in physical registers.
3901     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3902       Register GPR = TheMachineFunction.addLiveIn(Reg, &X86::GR64RegClass);
3903       LiveGPRs.push_back(DAG.getCopyFromReg(Chain, DL, GPR, MVT::i64));
3904     }
3905     const auto &AvailableXmms = ArgXMMs.slice(NumXMMRegs);
3906     if (!AvailableXmms.empty()) {
3907       Register AL = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3908       ALVal = DAG.getCopyFromReg(Chain, DL, AL, MVT::i8);
3909       for (MCPhysReg Reg : AvailableXmms) {
3910         // FastRegisterAllocator spills virtual registers at basic
3911         // block boundary. That leads to usages of xmm registers
3912         // outside of check for %al. Pass physical registers to
3913         // VASTART_SAVE_XMM_REGS to avoid unneccessary spilling.
3914         TheMachineFunction.getRegInfo().addLiveIn(Reg);
3915         LiveXMMRegs.push_back(DAG.getRegister(Reg, MVT::v4f32));
3916       }
3917     }
3918 
3919     // Store the integer parameter registers.
3920     SmallVector<SDValue, 8> MemOps;
3921     SDValue RSFIN =
3922         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3923                           TargLowering.getPointerTy(DAG.getDataLayout()));
3924     unsigned Offset = FuncInfo->getVarArgsGPOffset();
3925     for (SDValue Val : LiveGPRs) {
3926       SDValue FIN = DAG.getNode(ISD::ADD, DL,
3927                                 TargLowering.getPointerTy(DAG.getDataLayout()),
3928                                 RSFIN, DAG.getIntPtrConstant(Offset, DL));
3929       SDValue Store =
3930           DAG.getStore(Val.getValue(1), DL, Val, FIN,
3931                        MachinePointerInfo::getFixedStack(
3932                            DAG.getMachineFunction(),
3933                            FuncInfo->getRegSaveFrameIndex(), Offset));
3934       MemOps.push_back(Store);
3935       Offset += 8;
3936     }
3937 
3938     // Now store the XMM (fp + vector) parameter registers.
3939     if (!LiveXMMRegs.empty()) {
3940       SmallVector<SDValue, 12> SaveXMMOps;
3941       SaveXMMOps.push_back(Chain);
3942       SaveXMMOps.push_back(ALVal);
3943       SaveXMMOps.push_back(RSFIN);
3944       SaveXMMOps.push_back(
3945           DAG.getTargetConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32));
3946       llvm::append_range(SaveXMMOps, LiveXMMRegs);
3947       MachineMemOperand *StoreMMO =
3948           DAG.getMachineFunction().getMachineMemOperand(
3949               MachinePointerInfo::getFixedStack(
3950                   DAG.getMachineFunction(), FuncInfo->getRegSaveFrameIndex(),
3951                   Offset),
3952               MachineMemOperand::MOStore, 128, Align(16));
3953       MemOps.push_back(DAG.getMemIntrinsicNode(X86ISD::VASTART_SAVE_XMM_REGS,
3954                                                DL, DAG.getVTList(MVT::Other),
3955                                                SaveXMMOps, MVT::i8, StoreMMO));
3956     }
3957 
3958     if (!MemOps.empty())
3959       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3960   }
3961 }
3962 
3963 void VarArgsLoweringHelper::forwardMustTailParameters(SDValue &Chain) {
3964   // Find the largest legal vector type.
3965   MVT VecVT = MVT::Other;
3966   // FIXME: Only some x86_32 calling conventions support AVX512.
3967   if (Subtarget.useAVX512Regs() &&
3968       (is64Bit() || (CallConv == CallingConv::X86_VectorCall ||
3969                      CallConv == CallingConv::Intel_OCL_BI)))
3970     VecVT = MVT::v16f32;
3971   else if (Subtarget.hasAVX())
3972     VecVT = MVT::v8f32;
3973   else if (Subtarget.hasSSE2())
3974     VecVT = MVT::v4f32;
3975 
3976   // We forward some GPRs and some vector types.
3977   SmallVector<MVT, 2> RegParmTypes;
3978   MVT IntVT = is64Bit() ? MVT::i64 : MVT::i32;
3979   RegParmTypes.push_back(IntVT);
3980   if (VecVT != MVT::Other)
3981     RegParmTypes.push_back(VecVT);
3982 
3983   // Compute the set of forwarded registers. The rest are scratch.
3984   SmallVectorImpl<ForwardedRegister> &Forwards =
3985       FuncInfo->getForwardedMustTailRegParms();
3986   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3987 
3988   // Forward AL for SysV x86_64 targets, since it is used for varargs.
3989   if (is64Bit() && !isWin64() && !CCInfo.isAllocated(X86::AL)) {
3990     Register ALVReg = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3991     Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3992   }
3993 
3994   // Copy all forwards from physical to virtual registers.
3995   for (ForwardedRegister &FR : Forwards) {
3996     // FIXME: Can we use a less constrained schedule?
3997     SDValue RegVal = DAG.getCopyFromReg(Chain, DL, FR.VReg, FR.VT);
3998     FR.VReg = TheMachineFunction.getRegInfo().createVirtualRegister(
3999         TargLowering.getRegClassFor(FR.VT));
4000     Chain = DAG.getCopyToReg(Chain, DL, FR.VReg, RegVal);
4001   }
4002 }
4003 
4004 void VarArgsLoweringHelper::lowerVarArgsParameters(SDValue &Chain,
4005                                                    unsigned StackSize) {
4006   // Set FrameIndex to the 0xAAAAAAA value to mark unset state.
4007   // If necessary, it would be set into the correct value later.
4008   FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
4009   FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
4010 
4011   if (FrameInfo.hasVAStart())
4012     createVarArgAreaAndStoreRegisters(Chain, StackSize);
4013 
4014   if (FrameInfo.hasMustTailInVarArgFunc())
4015     forwardMustTailParameters(Chain);
4016 }
4017 
4018 SDValue X86TargetLowering::LowerFormalArguments(
4019     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
4020     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4021     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4022   MachineFunction &MF = DAG.getMachineFunction();
4023   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4024 
4025   const Function &F = MF.getFunction();
4026   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
4027       F.getName() == "main")
4028     FuncInfo->setForceFramePointer(true);
4029 
4030   MachineFrameInfo &MFI = MF.getFrameInfo();
4031   bool Is64Bit = Subtarget.is64Bit();
4032   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
4033 
4034   assert(
4035       !(IsVarArg && canGuaranteeTCO(CallConv)) &&
4036       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
4037 
4038   // Assign locations to all of the incoming arguments.
4039   SmallVector<CCValAssign, 16> ArgLocs;
4040   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
4041 
4042   // Allocate shadow area for Win64.
4043   if (IsWin64)
4044     CCInfo.AllocateStack(32, Align(8));
4045 
4046   CCInfo.AnalyzeArguments(Ins, CC_X86);
4047 
4048   // In vectorcall calling convention a second pass is required for the HVA
4049   // types.
4050   if (CallingConv::X86_VectorCall == CallConv) {
4051     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
4052   }
4053 
4054   // The next loop assumes that the locations are in the same order of the
4055   // input arguments.
4056   assert(isSortedByValueNo(ArgLocs) &&
4057          "Argument Location list must be sorted before lowering");
4058 
4059   SDValue ArgValue;
4060   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
4061        ++I, ++InsIndex) {
4062     assert(InsIndex < Ins.size() && "Invalid Ins index");
4063     CCValAssign &VA = ArgLocs[I];
4064 
4065     if (VA.isRegLoc()) {
4066       EVT RegVT = VA.getLocVT();
4067       if (VA.needsCustom()) {
4068         assert(
4069             VA.getValVT() == MVT::v64i1 &&
4070             "Currently the only custom case is when we split v64i1 to 2 regs");
4071 
4072         // v64i1 values, in regcall calling convention, that are
4073         // compiled to 32 bit arch, are split up into two registers.
4074         ArgValue =
4075             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
4076       } else {
4077         const TargetRegisterClass *RC;
4078         if (RegVT == MVT::i8)
4079           RC = &X86::GR8RegClass;
4080         else if (RegVT == MVT::i16)
4081           RC = &X86::GR16RegClass;
4082         else if (RegVT == MVT::i32)
4083           RC = &X86::GR32RegClass;
4084         else if (Is64Bit && RegVT == MVT::i64)
4085           RC = &X86::GR64RegClass;
4086         else if (RegVT == MVT::f16)
4087           RC = Subtarget.hasAVX512() ? &X86::FR16XRegClass : &X86::FR16RegClass;
4088         else if (RegVT == MVT::f32)
4089           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
4090         else if (RegVT == MVT::f64)
4091           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
4092         else if (RegVT == MVT::f80)
4093           RC = &X86::RFP80RegClass;
4094         else if (RegVT == MVT::f128)
4095           RC = &X86::VR128RegClass;
4096         else if (RegVT.is512BitVector())
4097           RC = &X86::VR512RegClass;
4098         else if (RegVT.is256BitVector())
4099           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
4100         else if (RegVT.is128BitVector())
4101           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
4102         else if (RegVT == MVT::x86mmx)
4103           RC = &X86::VR64RegClass;
4104         else if (RegVT == MVT::v1i1)
4105           RC = &X86::VK1RegClass;
4106         else if (RegVT == MVT::v8i1)
4107           RC = &X86::VK8RegClass;
4108         else if (RegVT == MVT::v16i1)
4109           RC = &X86::VK16RegClass;
4110         else if (RegVT == MVT::v32i1)
4111           RC = &X86::VK32RegClass;
4112         else if (RegVT == MVT::v64i1)
4113           RC = &X86::VK64RegClass;
4114         else
4115           llvm_unreachable("Unknown argument type!");
4116 
4117         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4118         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4119       }
4120 
4121       // If this is an 8 or 16-bit value, it is really passed promoted to 32
4122       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
4123       // right size.
4124       if (VA.getLocInfo() == CCValAssign::SExt)
4125         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4126                                DAG.getValueType(VA.getValVT()));
4127       else if (VA.getLocInfo() == CCValAssign::ZExt)
4128         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4129                                DAG.getValueType(VA.getValVT()));
4130       else if (VA.getLocInfo() == CCValAssign::BCvt)
4131         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
4132 
4133       if (VA.isExtInLoc()) {
4134         // Handle MMX values passed in XMM regs.
4135         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
4136           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
4137         else if (VA.getValVT().isVector() &&
4138                  VA.getValVT().getScalarType() == MVT::i1 &&
4139                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
4140                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
4141           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
4142           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
4143         } else
4144           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4145       }
4146     } else {
4147       assert(VA.isMemLoc());
4148       ArgValue =
4149           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
4150     }
4151 
4152     // If value is passed via pointer - do a load.
4153     if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
4154       ArgValue =
4155           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
4156 
4157     InVals.push_back(ArgValue);
4158   }
4159 
4160   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4161     if (Ins[I].Flags.isSwiftAsync()) {
4162       auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
4163       if (Subtarget.is64Bit())
4164         X86FI->setHasSwiftAsyncContext(true);
4165       else {
4166         int FI = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
4167         X86FI->setSwiftAsyncContextFrameIdx(FI);
4168         SDValue St = DAG.getStore(DAG.getEntryNode(), dl, InVals[I],
4169                                   DAG.getFrameIndex(FI, MVT::i32),
4170                                   MachinePointerInfo::getFixedStack(MF, FI));
4171         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, St, Chain);
4172       }
4173     }
4174 
4175     // Swift calling convention does not require we copy the sret argument
4176     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
4177     if (CallConv == CallingConv::Swift || CallConv == CallingConv::SwiftTail)
4178       continue;
4179 
4180     // All x86 ABIs require that for returning structs by value we copy the
4181     // sret argument into %rax/%eax (depending on ABI) for the return. Save
4182     // the argument into a virtual register so that we can access it from the
4183     // return points.
4184     if (Ins[I].Flags.isSRet()) {
4185       assert(!FuncInfo->getSRetReturnReg() &&
4186              "SRet return has already been set");
4187       MVT PtrTy = getPointerTy(DAG.getDataLayout());
4188       Register Reg =
4189           MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4190       FuncInfo->setSRetReturnReg(Reg);
4191       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
4192       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
4193       break;
4194     }
4195   }
4196 
4197   unsigned StackSize = CCInfo.getNextStackOffset();
4198   // Align stack specially for tail calls.
4199   if (shouldGuaranteeTCO(CallConv,
4200                          MF.getTarget().Options.GuaranteedTailCallOpt))
4201     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
4202 
4203   if (IsVarArg)
4204     VarArgsLoweringHelper(FuncInfo, dl, DAG, Subtarget, CallConv, CCInfo)
4205         .lowerVarArgsParameters(Chain, StackSize);
4206 
4207   // Some CCs need callee pop.
4208   if (X86::isCalleePop(CallConv, Is64Bit, IsVarArg,
4209                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
4210     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
4211   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
4212     // X86 interrupts must pop the error code (and the alignment padding) if
4213     // present.
4214     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
4215   } else {
4216     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
4217     // If this is an sret function, the return should pop the hidden pointer.
4218     if (!canGuaranteeTCO(CallConv) && hasCalleePopSRet(Ins, Subtarget))
4219       FuncInfo->setBytesToPopOnReturn(4);
4220   }
4221 
4222   if (!Is64Bit) {
4223     // RegSaveFrameIndex is X86-64 only.
4224     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
4225   }
4226 
4227   FuncInfo->setArgumentStackSize(StackSize);
4228 
4229   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
4230     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
4231     if (Personality == EHPersonality::CoreCLR) {
4232       assert(Is64Bit);
4233       // TODO: Add a mechanism to frame lowering that will allow us to indicate
4234       // that we'd prefer this slot be allocated towards the bottom of the frame
4235       // (i.e. near the stack pointer after allocating the frame).  Every
4236       // funclet needs a copy of this slot in its (mostly empty) frame, and the
4237       // offset from the bottom of this and each funclet's frame must be the
4238       // same, so the size of funclets' (mostly empty) frames is dictated by
4239       // how far this slot is from the bottom (since they allocate just enough
4240       // space to accommodate holding this slot at the correct offset).
4241       int PSPSymFI = MFI.CreateStackObject(8, Align(8), /*isSpillSlot=*/false);
4242       EHInfo->PSPSymFrameIdx = PSPSymFI;
4243     }
4244   }
4245 
4246   if (CallConv == CallingConv::X86_RegCall ||
4247       F.hasFnAttribute("no_caller_saved_registers")) {
4248     MachineRegisterInfo &MRI = MF.getRegInfo();
4249     for (std::pair<Register, Register> Pair : MRI.liveins())
4250       MRI.disableCalleeSavedRegister(Pair.first);
4251   }
4252 
4253   return Chain;
4254 }
4255 
4256 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
4257                                             SDValue Arg, const SDLoc &dl,
4258                                             SelectionDAG &DAG,
4259                                             const CCValAssign &VA,
4260                                             ISD::ArgFlagsTy Flags,
4261                                             bool isByVal) const {
4262   unsigned LocMemOffset = VA.getLocMemOffset();
4263   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4264   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4265                        StackPtr, PtrOff);
4266   if (isByVal)
4267     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
4268 
4269   MaybeAlign Alignment;
4270   if (Subtarget.isTargetWindowsMSVC() && !Subtarget.is64Bit() &&
4271       Arg.getSimpleValueType() != MVT::f80)
4272     Alignment = MaybeAlign(4);
4273   return DAG.getStore(
4274       Chain, dl, Arg, PtrOff,
4275       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
4276       Alignment);
4277 }
4278 
4279 /// Emit a load of return address if tail call
4280 /// optimization is performed and it is required.
4281 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
4282     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
4283     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
4284   // Adjust the Return address stack slot.
4285   EVT VT = getPointerTy(DAG.getDataLayout());
4286   OutRetAddr = getReturnAddressFrameIndex(DAG);
4287 
4288   // Load the "old" Return address.
4289   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
4290   return SDValue(OutRetAddr.getNode(), 1);
4291 }
4292 
4293 /// Emit a store of the return address if tail call
4294 /// optimization is performed and it is required (FPDiff!=0).
4295 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
4296                                         SDValue Chain, SDValue RetAddrFrIdx,
4297                                         EVT PtrVT, unsigned SlotSize,
4298                                         int FPDiff, const SDLoc &dl) {
4299   // Store the return address to the appropriate stack slot.
4300   if (!FPDiff) return Chain;
4301   // Calculate the new stack slot for the return address.
4302   int NewReturnAddrFI =
4303     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
4304                                          false);
4305   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
4306   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
4307                        MachinePointerInfo::getFixedStack(
4308                            DAG.getMachineFunction(), NewReturnAddrFI));
4309   return Chain;
4310 }
4311 
4312 /// Returns a vector_shuffle mask for an movs{s|d}, movd
4313 /// operation of specified width.
4314 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
4315                        SDValue V2) {
4316   unsigned NumElems = VT.getVectorNumElements();
4317   SmallVector<int, 8> Mask;
4318   Mask.push_back(NumElems);
4319   for (unsigned i = 1; i != NumElems; ++i)
4320     Mask.push_back(i);
4321   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4322 }
4323 
4324 SDValue
4325 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4326                              SmallVectorImpl<SDValue> &InVals) const {
4327   SelectionDAG &DAG                     = CLI.DAG;
4328   SDLoc &dl                             = CLI.DL;
4329   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4330   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4331   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4332   SDValue Chain                         = CLI.Chain;
4333   SDValue Callee                        = CLI.Callee;
4334   CallingConv::ID CallConv              = CLI.CallConv;
4335   bool &isTailCall                      = CLI.IsTailCall;
4336   bool isVarArg                         = CLI.IsVarArg;
4337   const auto *CB                        = CLI.CB;
4338 
4339   MachineFunction &MF = DAG.getMachineFunction();
4340   bool Is64Bit        = Subtarget.is64Bit();
4341   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
4342   bool IsSibcall      = false;
4343   bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
4344       CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
4345   bool IsCalleePopSRet = !IsGuaranteeTCO && hasCalleePopSRet(Outs, Subtarget);
4346   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
4347   bool HasNCSR = (CB && isa<CallInst>(CB) &&
4348                   CB->hasFnAttr("no_caller_saved_registers"));
4349   bool HasNoCfCheck = (CB && CB->doesNoCfCheck());
4350   bool IsIndirectCall = (CB && isa<CallInst>(CB) && CB->isIndirectCall());
4351   const Module *M = MF.getMMI().getModule();
4352   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
4353 
4354   MachineFunction::CallSiteInfo CSInfo;
4355   if (CallConv == CallingConv::X86_INTR)
4356     report_fatal_error("X86 interrupts may not be called directly");
4357 
4358   bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
4359   if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO && !IsMustTail) {
4360     // If we are using a GOT, disable tail calls to external symbols with
4361     // default visibility. Tail calling such a symbol requires using a GOT
4362     // relocation, which forces early binding of the symbol. This breaks code
4363     // that require lazy function symbol resolution. Using musttail or
4364     // GuaranteedTailCallOpt will override this.
4365     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4366     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
4367                G->getGlobal()->hasDefaultVisibility()))
4368       isTailCall = false;
4369   }
4370 
4371   if (isTailCall && !IsMustTail) {
4372     // Check if it's really possible to do a tail call.
4373     isTailCall = IsEligibleForTailCallOptimization(
4374         Callee, CallConv, IsCalleePopSRet, isVarArg, CLI.RetTy, Outs, OutVals,
4375         Ins, DAG);
4376 
4377     // Sibcalls are automatically detected tailcalls which do not require
4378     // ABI changes.
4379     if (!IsGuaranteeTCO && isTailCall)
4380       IsSibcall = true;
4381 
4382     if (isTailCall)
4383       ++NumTailCalls;
4384   }
4385 
4386   if (IsMustTail && !isTailCall)
4387     report_fatal_error("failed to perform tail call elimination on a call "
4388                        "site marked musttail");
4389 
4390   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
4391          "Var args not supported with calling convention fastcc, ghc or hipe");
4392 
4393   // Analyze operands of the call, assigning locations to each operand.
4394   SmallVector<CCValAssign, 16> ArgLocs;
4395   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4396 
4397   // Allocate shadow area for Win64.
4398   if (IsWin64)
4399     CCInfo.AllocateStack(32, Align(8));
4400 
4401   CCInfo.AnalyzeArguments(Outs, CC_X86);
4402 
4403   // In vectorcall calling convention a second pass is required for the HVA
4404   // types.
4405   if (CallingConv::X86_VectorCall == CallConv) {
4406     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
4407   }
4408 
4409   // Get a count of how many bytes are to be pushed on the stack.
4410   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
4411   if (IsSibcall)
4412     // This is a sibcall. The memory operands are available in caller's
4413     // own caller's stack.
4414     NumBytes = 0;
4415   else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
4416     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
4417 
4418   int FPDiff = 0;
4419   if (isTailCall &&
4420       shouldGuaranteeTCO(CallConv,
4421                          MF.getTarget().Options.GuaranteedTailCallOpt)) {
4422     // Lower arguments at fp - stackoffset + fpdiff.
4423     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
4424 
4425     FPDiff = NumBytesCallerPushed - NumBytes;
4426 
4427     // Set the delta of movement of the returnaddr stackslot.
4428     // But only set if delta is greater than previous delta.
4429     if (FPDiff < X86Info->getTCReturnAddrDelta())
4430       X86Info->setTCReturnAddrDelta(FPDiff);
4431   }
4432 
4433   unsigned NumBytesToPush = NumBytes;
4434   unsigned NumBytesToPop = NumBytes;
4435 
4436   // If we have an inalloca argument, all stack space has already been allocated
4437   // for us and be right at the top of the stack.  We don't support multiple
4438   // arguments passed in memory when using inalloca.
4439   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
4440     NumBytesToPush = 0;
4441     if (!ArgLocs.back().isMemLoc())
4442       report_fatal_error("cannot use inalloca attribute on a register "
4443                          "parameter");
4444     if (ArgLocs.back().getLocMemOffset() != 0)
4445       report_fatal_error("any parameter with the inalloca attribute must be "
4446                          "the only memory argument");
4447   } else if (CLI.IsPreallocated) {
4448     assert(ArgLocs.back().isMemLoc() &&
4449            "cannot use preallocated attribute on a register "
4450            "parameter");
4451     SmallVector<size_t, 4> PreallocatedOffsets;
4452     for (size_t i = 0; i < CLI.OutVals.size(); ++i) {
4453       if (CLI.CB->paramHasAttr(i, Attribute::Preallocated)) {
4454         PreallocatedOffsets.push_back(ArgLocs[i].getLocMemOffset());
4455       }
4456     }
4457     auto *MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
4458     size_t PreallocatedId = MFI->getPreallocatedIdForCallSite(CLI.CB);
4459     MFI->setPreallocatedStackSize(PreallocatedId, NumBytes);
4460     MFI->setPreallocatedArgOffsets(PreallocatedId, PreallocatedOffsets);
4461     NumBytesToPush = 0;
4462   }
4463 
4464   if (!IsSibcall && !IsMustTail)
4465     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
4466                                  NumBytes - NumBytesToPush, dl);
4467 
4468   SDValue RetAddrFrIdx;
4469   // Load return address for tail calls.
4470   if (isTailCall && FPDiff)
4471     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
4472                                     Is64Bit, FPDiff, dl);
4473 
4474   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
4475   SmallVector<SDValue, 8> MemOpChains;
4476   SDValue StackPtr;
4477 
4478   // The next loop assumes that the locations are in the same order of the
4479   // input arguments.
4480   assert(isSortedByValueNo(ArgLocs) &&
4481          "Argument Location list must be sorted before lowering");
4482 
4483   // Walk the register/memloc assignments, inserting copies/loads.  In the case
4484   // of tail call optimization arguments are handle later.
4485   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4486   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
4487        ++I, ++OutIndex) {
4488     assert(OutIndex < Outs.size() && "Invalid Out index");
4489     // Skip inalloca/preallocated arguments, they have already been written.
4490     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
4491     if (Flags.isInAlloca() || Flags.isPreallocated())
4492       continue;
4493 
4494     CCValAssign &VA = ArgLocs[I];
4495     EVT RegVT = VA.getLocVT();
4496     SDValue Arg = OutVals[OutIndex];
4497     bool isByVal = Flags.isByVal();
4498 
4499     // Promote the value if needed.
4500     switch (VA.getLocInfo()) {
4501     default: llvm_unreachable("Unknown loc info!");
4502     case CCValAssign::Full: break;
4503     case CCValAssign::SExt:
4504       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
4505       break;
4506     case CCValAssign::ZExt:
4507       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
4508       break;
4509     case CCValAssign::AExt:
4510       if (Arg.getValueType().isVector() &&
4511           Arg.getValueType().getVectorElementType() == MVT::i1)
4512         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
4513       else if (RegVT.is128BitVector()) {
4514         // Special case: passing MMX values in XMM registers.
4515         Arg = DAG.getBitcast(MVT::i64, Arg);
4516         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
4517         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
4518       } else
4519         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
4520       break;
4521     case CCValAssign::BCvt:
4522       Arg = DAG.getBitcast(RegVT, Arg);
4523       break;
4524     case CCValAssign::Indirect: {
4525       if (isByVal) {
4526         // Memcpy the argument to a temporary stack slot to prevent
4527         // the caller from seeing any modifications the callee may make
4528         // as guaranteed by the `byval` attribute.
4529         int FrameIdx = MF.getFrameInfo().CreateStackObject(
4530             Flags.getByValSize(),
4531             std::max(Align(16), Flags.getNonZeroByValAlign()), false);
4532         SDValue StackSlot =
4533             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
4534         Chain =
4535             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
4536         // From now on treat this as a regular pointer
4537         Arg = StackSlot;
4538         isByVal = false;
4539       } else {
4540         // Store the argument.
4541         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
4542         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
4543         Chain = DAG.getStore(
4544             Chain, dl, Arg, SpillSlot,
4545             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4546         Arg = SpillSlot;
4547       }
4548       break;
4549     }
4550     }
4551 
4552     if (VA.needsCustom()) {
4553       assert(VA.getValVT() == MVT::v64i1 &&
4554              "Currently the only custom case is when we split v64i1 to 2 regs");
4555       // Split v64i1 value into two registers
4556       Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
4557     } else if (VA.isRegLoc()) {
4558       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4559       const TargetOptions &Options = DAG.getTarget().Options;
4560       if (Options.EmitCallSiteInfo)
4561         CSInfo.emplace_back(VA.getLocReg(), I);
4562       if (isVarArg && IsWin64) {
4563         // Win64 ABI requires argument XMM reg to be copied to the corresponding
4564         // shadow reg if callee is a varargs function.
4565         Register ShadowReg;
4566         switch (VA.getLocReg()) {
4567         case X86::XMM0: ShadowReg = X86::RCX; break;
4568         case X86::XMM1: ShadowReg = X86::RDX; break;
4569         case X86::XMM2: ShadowReg = X86::R8; break;
4570         case X86::XMM3: ShadowReg = X86::R9; break;
4571         }
4572         if (ShadowReg)
4573           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4574       }
4575     } else if (!IsSibcall && (!isTailCall || isByVal)) {
4576       assert(VA.isMemLoc());
4577       if (!StackPtr.getNode())
4578         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4579                                       getPointerTy(DAG.getDataLayout()));
4580       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4581                                              dl, DAG, VA, Flags, isByVal));
4582     }
4583   }
4584 
4585   if (!MemOpChains.empty())
4586     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4587 
4588   if (Subtarget.isPICStyleGOT()) {
4589     // ELF / PIC requires GOT in the EBX register before function calls via PLT
4590     // GOT pointer (except regcall).
4591     if (!isTailCall) {
4592       // Indirect call with RegCall calling convertion may use up all the
4593       // general registers, so it is not suitable to bind EBX reister for
4594       // GOT address, just let register allocator handle it.
4595       if (CallConv != CallingConv::X86_RegCall)
4596         RegsToPass.push_back(std::make_pair(
4597           Register(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4598                                           getPointerTy(DAG.getDataLayout()))));
4599     } else {
4600       // If we are tail calling and generating PIC/GOT style code load the
4601       // address of the callee into ECX. The value in ecx is used as target of
4602       // the tail jump. This is done to circumvent the ebx/callee-saved problem
4603       // for tail calls on PIC/GOT architectures. Normally we would just put the
4604       // address of GOT into ebx and then call target@PLT. But for tail calls
4605       // ebx would be restored (since ebx is callee saved) before jumping to the
4606       // target@PLT.
4607 
4608       // Note: The actual moving to ECX is done further down.
4609       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4610       if (G && !G->getGlobal()->hasLocalLinkage() &&
4611           G->getGlobal()->hasDefaultVisibility())
4612         Callee = LowerGlobalAddress(Callee, DAG);
4613       else if (isa<ExternalSymbolSDNode>(Callee))
4614         Callee = LowerExternalSymbol(Callee, DAG);
4615     }
4616   }
4617 
4618   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail &&
4619       (Subtarget.hasSSE1() || !M->getModuleFlag("SkipRaxSetup"))) {
4620     // From AMD64 ABI document:
4621     // For calls that may call functions that use varargs or stdargs
4622     // (prototype-less calls or calls to functions containing ellipsis (...) in
4623     // the declaration) %al is used as hidden argument to specify the number
4624     // of SSE registers used. The contents of %al do not need to match exactly
4625     // the number of registers, but must be an ubound on the number of SSE
4626     // registers used and is in the range 0 - 8 inclusive.
4627 
4628     // Count the number of XMM registers allocated.
4629     static const MCPhysReg XMMArgRegs[] = {
4630       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4631       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4632     };
4633     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4634     assert((Subtarget.hasSSE1() || !NumXMMRegs)
4635            && "SSE registers cannot be used when SSE is disabled");
4636     RegsToPass.push_back(std::make_pair(Register(X86::AL),
4637                                         DAG.getConstant(NumXMMRegs, dl,
4638                                                         MVT::i8)));
4639   }
4640 
4641   if (isVarArg && IsMustTail) {
4642     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4643     for (const auto &F : Forwards) {
4644       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4645       RegsToPass.push_back(std::make_pair(F.PReg, Val));
4646     }
4647   }
4648 
4649   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
4650   // don't need this because the eligibility check rejects calls that require
4651   // shuffling arguments passed in memory.
4652   if (!IsSibcall && isTailCall) {
4653     // Force all the incoming stack arguments to be loaded from the stack
4654     // before any new outgoing arguments are stored to the stack, because the
4655     // outgoing stack slots may alias the incoming argument stack slots, and
4656     // the alias isn't otherwise explicit. This is slightly more conservative
4657     // than necessary, because it means that each store effectively depends
4658     // on every argument instead of just those arguments it would clobber.
4659     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4660 
4661     SmallVector<SDValue, 8> MemOpChains2;
4662     SDValue FIN;
4663     int FI = 0;
4664     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4665          ++I, ++OutsIndex) {
4666       CCValAssign &VA = ArgLocs[I];
4667 
4668       if (VA.isRegLoc()) {
4669         if (VA.needsCustom()) {
4670           assert((CallConv == CallingConv::X86_RegCall) &&
4671                  "Expecting custom case only in regcall calling convention");
4672           // This means that we are in special case where one argument was
4673           // passed through two register locations - Skip the next location
4674           ++I;
4675         }
4676 
4677         continue;
4678       }
4679 
4680       assert(VA.isMemLoc());
4681       SDValue Arg = OutVals[OutsIndex];
4682       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4683       // Skip inalloca/preallocated arguments.  They don't require any work.
4684       if (Flags.isInAlloca() || Flags.isPreallocated())
4685         continue;
4686       // Create frame index.
4687       int32_t Offset = VA.getLocMemOffset()+FPDiff;
4688       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4689       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4690       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4691 
4692       if (Flags.isByVal()) {
4693         // Copy relative to framepointer.
4694         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4695         if (!StackPtr.getNode())
4696           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4697                                         getPointerTy(DAG.getDataLayout()));
4698         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4699                              StackPtr, Source);
4700 
4701         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4702                                                          ArgChain,
4703                                                          Flags, DAG, dl));
4704       } else {
4705         // Store relative to framepointer.
4706         MemOpChains2.push_back(DAG.getStore(
4707             ArgChain, dl, Arg, FIN,
4708             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4709       }
4710     }
4711 
4712     if (!MemOpChains2.empty())
4713       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4714 
4715     // Store the return address to the appropriate stack slot.
4716     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4717                                      getPointerTy(DAG.getDataLayout()),
4718                                      RegInfo->getSlotSize(), FPDiff, dl);
4719   }
4720 
4721   // Build a sequence of copy-to-reg nodes chained together with token chain
4722   // and flag operands which copy the outgoing args into registers.
4723   SDValue InFlag;
4724   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4725     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4726                              RegsToPass[i].second, InFlag);
4727     InFlag = Chain.getValue(1);
4728   }
4729 
4730   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4731     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
4732     // In the 64-bit large code model, we have to make all calls
4733     // through a register, since the call instruction's 32-bit
4734     // pc-relative offset may not be large enough to hold the whole
4735     // address.
4736   } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4737              Callee->getOpcode() == ISD::ExternalSymbol) {
4738     // Lower direct calls to global addresses and external symbols. Setting
4739     // ForCall to true here has the effect of removing WrapperRIP when possible
4740     // to allow direct calls to be selected without first materializing the
4741     // address into a register.
4742     Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4743   } else if (Subtarget.isTarget64BitILP32() &&
4744              Callee.getValueType() == MVT::i32) {
4745     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4746     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4747   }
4748 
4749   // Returns a chain & a flag for retval copy to use.
4750   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4751   SmallVector<SDValue, 8> Ops;
4752 
4753   if (!IsSibcall && isTailCall && !IsMustTail) {
4754     Chain = DAG.getCALLSEQ_END(Chain,
4755                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4756                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4757     InFlag = Chain.getValue(1);
4758   }
4759 
4760   Ops.push_back(Chain);
4761   Ops.push_back(Callee);
4762 
4763   if (isTailCall)
4764     Ops.push_back(DAG.getTargetConstant(FPDiff, dl, MVT::i32));
4765 
4766   // Add argument registers to the end of the list so that they are known live
4767   // into the call.
4768   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4769     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4770                                   RegsToPass[i].second.getValueType()));
4771 
4772   // Add a register mask operand representing the call-preserved registers.
4773   const uint32_t *Mask = [&]() {
4774     auto AdaptedCC = CallConv;
4775     // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists),
4776     // use X86_INTR calling convention because it has the same CSR mask
4777     // (same preserved registers).
4778     if (HasNCSR)
4779       AdaptedCC = (CallingConv::ID)CallingConv::X86_INTR;
4780     // If NoCalleeSavedRegisters is requested, than use GHC since it happens
4781     // to use the CSR_NoRegs_RegMask.
4782     if (CB && CB->hasFnAttr("no_callee_saved_registers"))
4783       AdaptedCC = (CallingConv::ID)CallingConv::GHC;
4784     return RegInfo->getCallPreservedMask(MF, AdaptedCC);
4785   }();
4786   assert(Mask && "Missing call preserved mask for calling convention");
4787 
4788   // If this is an invoke in a 32-bit function using a funclet-based
4789   // personality, assume the function clobbers all registers. If an exception
4790   // is thrown, the runtime will not restore CSRs.
4791   // FIXME: Model this more precisely so that we can register allocate across
4792   // the normal edge and spill and fill across the exceptional edge.
4793   if (!Is64Bit && CLI.CB && isa<InvokeInst>(CLI.CB)) {
4794     const Function &CallerFn = MF.getFunction();
4795     EHPersonality Pers =
4796         CallerFn.hasPersonalityFn()
4797             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4798             : EHPersonality::Unknown;
4799     if (isFuncletEHPersonality(Pers))
4800       Mask = RegInfo->getNoPreservedMask();
4801   }
4802 
4803   // Define a new register mask from the existing mask.
4804   uint32_t *RegMask = nullptr;
4805 
4806   // In some calling conventions we need to remove the used physical registers
4807   // from the reg mask.
4808   if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4809     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4810 
4811     // Allocate a new Reg Mask and copy Mask.
4812     RegMask = MF.allocateRegMask();
4813     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4814     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4815 
4816     // Make sure all sub registers of the argument registers are reset
4817     // in the RegMask.
4818     for (auto const &RegPair : RegsToPass)
4819       for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4820            SubRegs.isValid(); ++SubRegs)
4821         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4822 
4823     // Create the RegMask Operand according to our updated mask.
4824     Ops.push_back(DAG.getRegisterMask(RegMask));
4825   } else {
4826     // Create the RegMask Operand according to the static mask.
4827     Ops.push_back(DAG.getRegisterMask(Mask));
4828   }
4829 
4830   if (InFlag.getNode())
4831     Ops.push_back(InFlag);
4832 
4833   if (isTailCall) {
4834     // We used to do:
4835     //// If this is the first return lowered for this function, add the regs
4836     //// to the liveout set for the function.
4837     // This isn't right, although it's probably harmless on x86; liveouts
4838     // should be computed from returns not tail calls.  Consider a void
4839     // function making a tail call to a function returning int.
4840     MF.getFrameInfo().setHasTailCall();
4841     SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4842     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4843     return Ret;
4844   }
4845 
4846   if (HasNoCfCheck && IsCFProtectionSupported && IsIndirectCall) {
4847     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4848   } else if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
4849     // Calls with a "clang.arc.attachedcall" bundle are special. They should be
4850     // expanded to the call, directly followed by a special marker sequence and
4851     // a call to a ObjC library function. Use the CALL_RVMARKER to do that.
4852     assert(!isTailCall &&
4853            "tail calls cannot be marked with clang.arc.attachedcall");
4854     assert(Is64Bit && "clang.arc.attachedcall is only supported in 64bit mode");
4855 
4856     // Add a target global address for the retainRV/claimRV runtime function
4857     // just before the call target.
4858     Function *ARCFn = *objcarc::getAttachedARCFunction(CLI.CB);
4859     auto PtrVT = getPointerTy(DAG.getDataLayout());
4860     auto GA = DAG.getTargetGlobalAddress(ARCFn, dl, PtrVT);
4861     Ops.insert(Ops.begin() + 1, GA);
4862     Chain = DAG.getNode(X86ISD::CALL_RVMARKER, dl, NodeTys, Ops);
4863   } else {
4864     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4865   }
4866 
4867   InFlag = Chain.getValue(1);
4868   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4869   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4870 
4871   // Save heapallocsite metadata.
4872   if (CLI.CB)
4873     if (MDNode *HeapAlloc = CLI.CB->getMetadata("heapallocsite"))
4874       DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4875 
4876   // Create the CALLSEQ_END node.
4877   unsigned NumBytesForCalleeToPop = 0; // Callee pops nothing.
4878   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4879                        DAG.getTarget().Options.GuaranteedTailCallOpt))
4880     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
4881   else if (!canGuaranteeTCO(CallConv) && IsCalleePopSRet)
4882     // If this call passes a struct-return pointer, the callee
4883     // pops that struct pointer.
4884     NumBytesForCalleeToPop = 4;
4885 
4886   // Returns a flag for retval copy to use.
4887   if (!IsSibcall) {
4888     Chain = DAG.getCALLSEQ_END(Chain,
4889                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4890                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4891                                                      true),
4892                                InFlag, dl);
4893     InFlag = Chain.getValue(1);
4894   }
4895 
4896   // Handle result values, copying them out of physregs into vregs that we
4897   // return.
4898   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4899                          InVals, RegMask);
4900 }
4901 
4902 //===----------------------------------------------------------------------===//
4903 //                Fast Calling Convention (tail call) implementation
4904 //===----------------------------------------------------------------------===//
4905 
4906 //  Like std call, callee cleans arguments, convention except that ECX is
4907 //  reserved for storing the tail called function address. Only 2 registers are
4908 //  free for argument passing (inreg). Tail call optimization is performed
4909 //  provided:
4910 //                * tailcallopt is enabled
4911 //                * caller/callee are fastcc
4912 //  On X86_64 architecture with GOT-style position independent code only local
4913 //  (within module) calls are supported at the moment.
4914 //  To keep the stack aligned according to platform abi the function
4915 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
4916 //  of stack alignment. (Dynamic linkers need this - Darwin's dyld for example)
4917 //  If a tail called function callee has more arguments than the caller the
4918 //  caller needs to make sure that there is room to move the RETADDR to. This is
4919 //  achieved by reserving an area the size of the argument delta right after the
4920 //  original RETADDR, but before the saved framepointer or the spilled registers
4921 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4922 //  stack layout:
4923 //    arg1
4924 //    arg2
4925 //    RETADDR
4926 //    [ new RETADDR
4927 //      move area ]
4928 //    (possible EBP)
4929 //    ESI
4930 //    EDI
4931 //    local1 ..
4932 
4933 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4934 /// requirement.
4935 unsigned
4936 X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
4937                                                SelectionDAG &DAG) const {
4938   const Align StackAlignment = Subtarget.getFrameLowering()->getStackAlign();
4939   const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
4940   assert(StackSize % SlotSize == 0 &&
4941          "StackSize must be a multiple of SlotSize");
4942   return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
4943 }
4944 
4945 /// Return true if the given stack call argument is already available in the
4946 /// same position (relatively) of the caller's incoming argument stack.
4947 static
4948 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4949                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4950                          const X86InstrInfo *TII, const CCValAssign &VA) {
4951   unsigned Bytes = Arg.getValueSizeInBits() / 8;
4952 
4953   for (;;) {
4954     // Look through nodes that don't alter the bits of the incoming value.
4955     unsigned Op = Arg.getOpcode();
4956     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4957       Arg = Arg.getOperand(0);
4958       continue;
4959     }
4960     if (Op == ISD::TRUNCATE) {
4961       const SDValue &TruncInput = Arg.getOperand(0);
4962       if (TruncInput.getOpcode() == ISD::AssertZext &&
4963           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4964               Arg.getValueType()) {
4965         Arg = TruncInput.getOperand(0);
4966         continue;
4967       }
4968     }
4969     break;
4970   }
4971 
4972   int FI = INT_MAX;
4973   if (Arg.getOpcode() == ISD::CopyFromReg) {
4974     Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4975     if (!VR.isVirtual())
4976       return false;
4977     MachineInstr *Def = MRI->getVRegDef(VR);
4978     if (!Def)
4979       return false;
4980     if (!Flags.isByVal()) {
4981       if (!TII->isLoadFromStackSlot(*Def, FI))
4982         return false;
4983     } else {
4984       unsigned Opcode = Def->getOpcode();
4985       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4986            Opcode == X86::LEA64_32r) &&
4987           Def->getOperand(1).isFI()) {
4988         FI = Def->getOperand(1).getIndex();
4989         Bytes = Flags.getByValSize();
4990       } else
4991         return false;
4992     }
4993   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4994     if (Flags.isByVal())
4995       // ByVal argument is passed in as a pointer but it's now being
4996       // dereferenced. e.g.
4997       // define @foo(%struct.X* %A) {
4998       //   tail call @bar(%struct.X* byval %A)
4999       // }
5000       return false;
5001     SDValue Ptr = Ld->getBasePtr();
5002     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
5003     if (!FINode)
5004       return false;
5005     FI = FINode->getIndex();
5006   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
5007     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
5008     FI = FINode->getIndex();
5009     Bytes = Flags.getByValSize();
5010   } else
5011     return false;
5012 
5013   assert(FI != INT_MAX);
5014   if (!MFI.isFixedObjectIndex(FI))
5015     return false;
5016 
5017   if (Offset != MFI.getObjectOffset(FI))
5018     return false;
5019 
5020   // If this is not byval, check that the argument stack object is immutable.
5021   // inalloca and argument copy elision can create mutable argument stack
5022   // objects. Byval objects can be mutated, but a byval call intends to pass the
5023   // mutated memory.
5024   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
5025     return false;
5026 
5027   if (VA.getLocVT().getFixedSizeInBits() >
5028       Arg.getValueSizeInBits().getFixedSize()) {
5029     // If the argument location is wider than the argument type, check that any
5030     // extension flags match.
5031     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
5032         Flags.isSExt() != MFI.isObjectSExt(FI)) {
5033       return false;
5034     }
5035   }
5036 
5037   return Bytes == MFI.getObjectSize(FI);
5038 }
5039 
5040 /// Check whether the call is eligible for tail call optimization. Targets
5041 /// that want to do tail call optimization should implement this function.
5042 bool X86TargetLowering::IsEligibleForTailCallOptimization(
5043     SDValue Callee, CallingConv::ID CalleeCC, bool IsCalleePopSRet,
5044     bool isVarArg, Type *RetTy, const SmallVectorImpl<ISD::OutputArg> &Outs,
5045     const SmallVectorImpl<SDValue> &OutVals,
5046     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
5047   if (!mayTailCallThisCC(CalleeCC))
5048     return false;
5049 
5050   // If -tailcallopt is specified, make fastcc functions tail-callable.
5051   MachineFunction &MF = DAG.getMachineFunction();
5052   const Function &CallerF = MF.getFunction();
5053 
5054   // If the function return type is x86_fp80 and the callee return type is not,
5055   // then the FP_EXTEND of the call result is not a nop. It's not safe to
5056   // perform a tailcall optimization here.
5057   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
5058     return false;
5059 
5060   CallingConv::ID CallerCC = CallerF.getCallingConv();
5061   bool CCMatch = CallerCC == CalleeCC;
5062   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
5063   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
5064   bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
5065       CalleeCC == CallingConv::Tail || CalleeCC == CallingConv::SwiftTail;
5066 
5067   // Win64 functions have extra shadow space for argument homing. Don't do the
5068   // sibcall if the caller and callee have mismatched expectations for this
5069   // space.
5070   if (IsCalleeWin64 != IsCallerWin64)
5071     return false;
5072 
5073   if (IsGuaranteeTCO) {
5074     if (canGuaranteeTCO(CalleeCC) && CCMatch)
5075       return true;
5076     return false;
5077   }
5078 
5079   // Look for obvious safe cases to perform tail call optimization that do not
5080   // require ABI changes. This is what gcc calls sibcall.
5081 
5082   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
5083   // emit a special epilogue.
5084   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
5085   if (RegInfo->hasStackRealignment(MF))
5086     return false;
5087 
5088   // Also avoid sibcall optimization if we're an sret return fn and the callee
5089   // is incompatible. See comment in LowerReturn about why hasStructRetAttr is
5090   // insufficient.
5091   if (MF.getInfo<X86MachineFunctionInfo>()->getSRetReturnReg()) {
5092     // For a compatible tail call the callee must return our sret pointer. So it
5093     // needs to be (a) an sret function itself and (b) we pass our sret as its
5094     // sret. Condition #b is harder to determine.
5095     return false;
5096   } else if (IsCalleePopSRet)
5097     // The callee pops an sret, so we cannot tail-call, as our caller doesn't
5098     // expect that.
5099     return false;
5100 
5101   // Do not sibcall optimize vararg calls unless all arguments are passed via
5102   // registers.
5103   LLVMContext &C = *DAG.getContext();
5104   if (isVarArg && !Outs.empty()) {
5105     // Optimizing for varargs on Win64 is unlikely to be safe without
5106     // additional testing.
5107     if (IsCalleeWin64 || IsCallerWin64)
5108       return false;
5109 
5110     SmallVector<CCValAssign, 16> ArgLocs;
5111     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5112 
5113     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
5114     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
5115       if (!ArgLocs[i].isRegLoc())
5116         return false;
5117   }
5118 
5119   // If the call result is in ST0 / ST1, it needs to be popped off the x87
5120   // stack.  Therefore, if it's not used by the call it is not safe to optimize
5121   // this into a sibcall.
5122   bool Unused = false;
5123   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5124     if (!Ins[i].Used) {
5125       Unused = true;
5126       break;
5127     }
5128   }
5129   if (Unused) {
5130     SmallVector<CCValAssign, 16> RVLocs;
5131     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
5132     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
5133     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5134       CCValAssign &VA = RVLocs[i];
5135       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
5136         return false;
5137     }
5138   }
5139 
5140   // Check that the call results are passed in the same way.
5141   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
5142                                   RetCC_X86, RetCC_X86))
5143     return false;
5144   // The callee has to preserve all registers the caller needs to preserve.
5145   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
5146   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5147   if (!CCMatch) {
5148     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5149     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5150       return false;
5151   }
5152 
5153   unsigned StackArgsSize = 0;
5154 
5155   // If the callee takes no arguments then go on to check the results of the
5156   // call.
5157   if (!Outs.empty()) {
5158     // Check if stack adjustment is needed. For now, do not do this if any
5159     // argument is passed on the stack.
5160     SmallVector<CCValAssign, 16> ArgLocs;
5161     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5162 
5163     // Allocate shadow area for Win64
5164     if (IsCalleeWin64)
5165       CCInfo.AllocateStack(32, Align(8));
5166 
5167     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
5168     StackArgsSize = CCInfo.getNextStackOffset();
5169 
5170     if (CCInfo.getNextStackOffset()) {
5171       // Check if the arguments are already laid out in the right way as
5172       // the caller's fixed stack objects.
5173       MachineFrameInfo &MFI = MF.getFrameInfo();
5174       const MachineRegisterInfo *MRI = &MF.getRegInfo();
5175       const X86InstrInfo *TII = Subtarget.getInstrInfo();
5176       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
5177         CCValAssign &VA = ArgLocs[i];
5178         SDValue Arg = OutVals[i];
5179         ISD::ArgFlagsTy Flags = Outs[i].Flags;
5180         if (VA.getLocInfo() == CCValAssign::Indirect)
5181           return false;
5182         if (!VA.isRegLoc()) {
5183           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
5184                                    MFI, MRI, TII, VA))
5185             return false;
5186         }
5187       }
5188     }
5189 
5190     bool PositionIndependent = isPositionIndependent();
5191     // If the tailcall address may be in a register, then make sure it's
5192     // possible to register allocate for it. In 32-bit, the call address can
5193     // only target EAX, EDX, or ECX since the tail call must be scheduled after
5194     // callee-saved registers are restored. These happen to be the same
5195     // registers used to pass 'inreg' arguments so watch out for those.
5196     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
5197                                   !isa<ExternalSymbolSDNode>(Callee)) ||
5198                                  PositionIndependent)) {
5199       unsigned NumInRegs = 0;
5200       // In PIC we need an extra register to formulate the address computation
5201       // for the callee.
5202       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
5203 
5204       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
5205         CCValAssign &VA = ArgLocs[i];
5206         if (!VA.isRegLoc())
5207           continue;
5208         Register Reg = VA.getLocReg();
5209         switch (Reg) {
5210         default: break;
5211         case X86::EAX: case X86::EDX: case X86::ECX:
5212           if (++NumInRegs == MaxInRegs)
5213             return false;
5214           break;
5215         }
5216       }
5217     }
5218 
5219     const MachineRegisterInfo &MRI = MF.getRegInfo();
5220     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
5221       return false;
5222   }
5223 
5224   bool CalleeWillPop =
5225       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
5226                        MF.getTarget().Options.GuaranteedTailCallOpt);
5227 
5228   if (unsigned BytesToPop =
5229           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
5230     // If we have bytes to pop, the callee must pop them.
5231     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
5232     if (!CalleePopMatches)
5233       return false;
5234   } else if (CalleeWillPop && StackArgsSize > 0) {
5235     // If we don't have bytes to pop, make sure the callee doesn't pop any.
5236     return false;
5237   }
5238 
5239   return true;
5240 }
5241 
5242 FastISel *
5243 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
5244                                   const TargetLibraryInfo *libInfo) const {
5245   return X86::createFastISel(funcInfo, libInfo);
5246 }
5247 
5248 //===----------------------------------------------------------------------===//
5249 //                           Other Lowering Hooks
5250 //===----------------------------------------------------------------------===//
5251 
5252 bool X86::mayFoldLoad(SDValue Op, const X86Subtarget &Subtarget,
5253                       bool AssumeSingleUse) {
5254   if (!AssumeSingleUse && !Op.hasOneUse())
5255     return false;
5256   if (!ISD::isNormalLoad(Op.getNode()))
5257     return false;
5258 
5259   // If this is an unaligned vector, make sure the target supports folding it.
5260   auto *Ld = cast<LoadSDNode>(Op.getNode());
5261   if (!Subtarget.hasAVX() && !Subtarget.hasSSEUnalignedMem() &&
5262       Ld->getValueSizeInBits(0) == 128 && Ld->getAlign() < Align(16))
5263     return false;
5264 
5265   // TODO: If this is a non-temporal load and the target has an instruction
5266   //       for it, it should not be folded. See "useNonTemporalLoad()".
5267 
5268   return true;
5269 }
5270 
5271 bool X86::mayFoldLoadIntoBroadcastFromMem(SDValue Op, MVT EltVT,
5272                                           const X86Subtarget &Subtarget,
5273                                           bool AssumeSingleUse) {
5274   assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
5275   if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
5276     return false;
5277 
5278   // We can not replace a wide volatile load with a broadcast-from-memory,
5279   // because that would narrow the load, which isn't legal for volatiles.
5280   auto *Ld = cast<LoadSDNode>(Op.getNode());
5281   return !Ld->isVolatile() ||
5282          Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
5283 }
5284 
5285 bool X86::mayFoldIntoStore(SDValue Op) {
5286   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
5287 }
5288 
5289 bool X86::mayFoldIntoZeroExtend(SDValue Op) {
5290   if (Op.hasOneUse()) {
5291     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
5292     return (ISD::ZERO_EXTEND == Opcode);
5293   }
5294   return false;
5295 }
5296 
5297 static bool isTargetShuffle(unsigned Opcode) {
5298   switch(Opcode) {
5299   default: return false;
5300   case X86ISD::BLENDI:
5301   case X86ISD::PSHUFB:
5302   case X86ISD::PSHUFD:
5303   case X86ISD::PSHUFHW:
5304   case X86ISD::PSHUFLW:
5305   case X86ISD::SHUFP:
5306   case X86ISD::INSERTPS:
5307   case X86ISD::EXTRQI:
5308   case X86ISD::INSERTQI:
5309   case X86ISD::VALIGN:
5310   case X86ISD::PALIGNR:
5311   case X86ISD::VSHLDQ:
5312   case X86ISD::VSRLDQ:
5313   case X86ISD::MOVLHPS:
5314   case X86ISD::MOVHLPS:
5315   case X86ISD::MOVSHDUP:
5316   case X86ISD::MOVSLDUP:
5317   case X86ISD::MOVDDUP:
5318   case X86ISD::MOVSS:
5319   case X86ISD::MOVSD:
5320   case X86ISD::MOVSH:
5321   case X86ISD::UNPCKL:
5322   case X86ISD::UNPCKH:
5323   case X86ISD::VBROADCAST:
5324   case X86ISD::VPERMILPI:
5325   case X86ISD::VPERMILPV:
5326   case X86ISD::VPERM2X128:
5327   case X86ISD::SHUF128:
5328   case X86ISD::VPERMIL2:
5329   case X86ISD::VPERMI:
5330   case X86ISD::VPPERM:
5331   case X86ISD::VPERMV:
5332   case X86ISD::VPERMV3:
5333   case X86ISD::VZEXT_MOVL:
5334     return true;
5335   }
5336 }
5337 
5338 static bool isTargetShuffleVariableMask(unsigned Opcode) {
5339   switch (Opcode) {
5340   default: return false;
5341   // Target Shuffles.
5342   case X86ISD::PSHUFB:
5343   case X86ISD::VPERMILPV:
5344   case X86ISD::VPERMIL2:
5345   case X86ISD::VPPERM:
5346   case X86ISD::VPERMV:
5347   case X86ISD::VPERMV3:
5348     return true;
5349   // 'Faux' Target Shuffles.
5350   case ISD::OR:
5351   case ISD::AND:
5352   case X86ISD::ANDNP:
5353     return true;
5354   }
5355 }
5356 
5357 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
5358   MachineFunction &MF = DAG.getMachineFunction();
5359   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
5360   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
5361   int ReturnAddrIndex = FuncInfo->getRAIndex();
5362 
5363   if (ReturnAddrIndex == 0) {
5364     // Set up a frame object for the return address.
5365     unsigned SlotSize = RegInfo->getSlotSize();
5366     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
5367                                                           -(int64_t)SlotSize,
5368                                                           false);
5369     FuncInfo->setRAIndex(ReturnAddrIndex);
5370   }
5371 
5372   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
5373 }
5374 
5375 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
5376                                        bool hasSymbolicDisplacement) {
5377   // Offset should fit into 32 bit immediate field.
5378   if (!isInt<32>(Offset))
5379     return false;
5380 
5381   // If we don't have a symbolic displacement - we don't have any extra
5382   // restrictions.
5383   if (!hasSymbolicDisplacement)
5384     return true;
5385 
5386   // FIXME: Some tweaks might be needed for medium code model.
5387   if (M != CodeModel::Small && M != CodeModel::Kernel)
5388     return false;
5389 
5390   // For small code model we assume that latest object is 16MB before end of 31
5391   // bits boundary. We may also accept pretty large negative constants knowing
5392   // that all objects are in the positive half of address space.
5393   if (M == CodeModel::Small && Offset < 16*1024*1024)
5394     return true;
5395 
5396   // For kernel code model we know that all object resist in the negative half
5397   // of 32bits address space. We may not accept negative offsets, since they may
5398   // be just off and we may accept pretty large positive ones.
5399   if (M == CodeModel::Kernel && Offset >= 0)
5400     return true;
5401 
5402   return false;
5403 }
5404 
5405 /// Determines whether the callee is required to pop its own arguments.
5406 /// Callee pop is necessary to support tail calls.
5407 bool X86::isCalleePop(CallingConv::ID CallingConv,
5408                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
5409   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
5410   // can guarantee TCO.
5411   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
5412     return true;
5413 
5414   switch (CallingConv) {
5415   default:
5416     return false;
5417   case CallingConv::X86_StdCall:
5418   case CallingConv::X86_FastCall:
5419   case CallingConv::X86_ThisCall:
5420   case CallingConv::X86_VectorCall:
5421     return !is64Bit;
5422   }
5423 }
5424 
5425 /// Return true if the condition is an signed comparison operation.
5426 static bool isX86CCSigned(unsigned X86CC) {
5427   switch (X86CC) {
5428   default:
5429     llvm_unreachable("Invalid integer condition!");
5430   case X86::COND_E:
5431   case X86::COND_NE:
5432   case X86::COND_B:
5433   case X86::COND_A:
5434   case X86::COND_BE:
5435   case X86::COND_AE:
5436     return false;
5437   case X86::COND_G:
5438   case X86::COND_GE:
5439   case X86::COND_L:
5440   case X86::COND_LE:
5441     return true;
5442   }
5443 }
5444 
5445 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
5446   switch (SetCCOpcode) {
5447   default: llvm_unreachable("Invalid integer condition!");
5448   case ISD::SETEQ:  return X86::COND_E;
5449   case ISD::SETGT:  return X86::COND_G;
5450   case ISD::SETGE:  return X86::COND_GE;
5451   case ISD::SETLT:  return X86::COND_L;
5452   case ISD::SETLE:  return X86::COND_LE;
5453   case ISD::SETNE:  return X86::COND_NE;
5454   case ISD::SETULT: return X86::COND_B;
5455   case ISD::SETUGT: return X86::COND_A;
5456   case ISD::SETULE: return X86::COND_BE;
5457   case ISD::SETUGE: return X86::COND_AE;
5458   }
5459 }
5460 
5461 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
5462 /// condition code, returning the condition code and the LHS/RHS of the
5463 /// comparison to make.
5464 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
5465                                     bool isFP, SDValue &LHS, SDValue &RHS,
5466                                     SelectionDAG &DAG) {
5467   if (!isFP) {
5468     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5469       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
5470         // X > -1   -> X == 0, jump !sign.
5471         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5472         return X86::COND_NS;
5473       }
5474       if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
5475         // X < 0   -> X == 0, jump on sign.
5476         return X86::COND_S;
5477       }
5478       if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
5479         // X >= 0   -> X == 0, jump on !sign.
5480         return X86::COND_NS;
5481       }
5482       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
5483         // X < 1   -> X <= 0
5484         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5485         return X86::COND_LE;
5486       }
5487     }
5488 
5489     return TranslateIntegerX86CC(SetCCOpcode);
5490   }
5491 
5492   // First determine if it is required or is profitable to flip the operands.
5493 
5494   // If LHS is a foldable load, but RHS is not, flip the condition.
5495   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
5496       !ISD::isNON_EXTLoad(RHS.getNode())) {
5497     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
5498     std::swap(LHS, RHS);
5499   }
5500 
5501   switch (SetCCOpcode) {
5502   default: break;
5503   case ISD::SETOLT:
5504   case ISD::SETOLE:
5505   case ISD::SETUGT:
5506   case ISD::SETUGE:
5507     std::swap(LHS, RHS);
5508     break;
5509   }
5510 
5511   // On a floating point condition, the flags are set as follows:
5512   // ZF  PF  CF   op
5513   //  0 | 0 | 0 | X > Y
5514   //  0 | 0 | 1 | X < Y
5515   //  1 | 0 | 0 | X == Y
5516   //  1 | 1 | 1 | unordered
5517   switch (SetCCOpcode) {
5518   default: llvm_unreachable("Condcode should be pre-legalized away");
5519   case ISD::SETUEQ:
5520   case ISD::SETEQ:   return X86::COND_E;
5521   case ISD::SETOLT:              // flipped
5522   case ISD::SETOGT:
5523   case ISD::SETGT:   return X86::COND_A;
5524   case ISD::SETOLE:              // flipped
5525   case ISD::SETOGE:
5526   case ISD::SETGE:   return X86::COND_AE;
5527   case ISD::SETUGT:              // flipped
5528   case ISD::SETULT:
5529   case ISD::SETLT:   return X86::COND_B;
5530   case ISD::SETUGE:              // flipped
5531   case ISD::SETULE:
5532   case ISD::SETLE:   return X86::COND_BE;
5533   case ISD::SETONE:
5534   case ISD::SETNE:   return X86::COND_NE;
5535   case ISD::SETUO:   return X86::COND_P;
5536   case ISD::SETO:    return X86::COND_NP;
5537   case ISD::SETOEQ:
5538   case ISD::SETUNE:  return X86::COND_INVALID;
5539   }
5540 }
5541 
5542 /// Is there a floating point cmov for the specific X86 condition code?
5543 /// Current x86 isa includes the following FP cmov instructions:
5544 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
5545 static bool hasFPCMov(unsigned X86CC) {
5546   switch (X86CC) {
5547   default:
5548     return false;
5549   case X86::COND_B:
5550   case X86::COND_BE:
5551   case X86::COND_E:
5552   case X86::COND_P:
5553   case X86::COND_A:
5554   case X86::COND_AE:
5555   case X86::COND_NE:
5556   case X86::COND_NP:
5557     return true;
5558   }
5559 }
5560 
5561 static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
5562   return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
5563          VT.is512BitVector();
5564 }
5565 
5566 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5567                                            const CallInst &I,
5568                                            MachineFunction &MF,
5569                                            unsigned Intrinsic) const {
5570   Info.flags = MachineMemOperand::MONone;
5571   Info.offset = 0;
5572 
5573   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
5574   if (!IntrData) {
5575     switch (Intrinsic) {
5576     case Intrinsic::x86_aesenc128kl:
5577     case Intrinsic::x86_aesdec128kl:
5578       Info.opc = ISD::INTRINSIC_W_CHAIN;
5579       Info.ptrVal = I.getArgOperand(1);
5580       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5581       Info.align = Align(1);
5582       Info.flags |= MachineMemOperand::MOLoad;
5583       return true;
5584     case Intrinsic::x86_aesenc256kl:
5585     case Intrinsic::x86_aesdec256kl:
5586       Info.opc = ISD::INTRINSIC_W_CHAIN;
5587       Info.ptrVal = I.getArgOperand(1);
5588       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5589       Info.align = Align(1);
5590       Info.flags |= MachineMemOperand::MOLoad;
5591       return true;
5592     case Intrinsic::x86_aesencwide128kl:
5593     case Intrinsic::x86_aesdecwide128kl:
5594       Info.opc = ISD::INTRINSIC_W_CHAIN;
5595       Info.ptrVal = I.getArgOperand(0);
5596       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5597       Info.align = Align(1);
5598       Info.flags |= MachineMemOperand::MOLoad;
5599       return true;
5600     case Intrinsic::x86_aesencwide256kl:
5601     case Intrinsic::x86_aesdecwide256kl:
5602       Info.opc = ISD::INTRINSIC_W_CHAIN;
5603       Info.ptrVal = I.getArgOperand(0);
5604       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5605       Info.align = Align(1);
5606       Info.flags |= MachineMemOperand::MOLoad;
5607       return true;
5608     case Intrinsic::x86_atomic_bts:
5609     case Intrinsic::x86_atomic_btc:
5610     case Intrinsic::x86_atomic_btr: {
5611       Info.opc = ISD::INTRINSIC_W_CHAIN;
5612       Info.ptrVal = I.getArgOperand(0);
5613       unsigned Size = I.getType()->getScalarSizeInBits();
5614       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
5615       Info.align = Align(Size);
5616       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
5617                     MachineMemOperand::MOVolatile;
5618       return true;
5619     }
5620     }
5621     return false;
5622   }
5623 
5624   switch (IntrData->Type) {
5625   case TRUNCATE_TO_MEM_VI8:
5626   case TRUNCATE_TO_MEM_VI16:
5627   case TRUNCATE_TO_MEM_VI32: {
5628     Info.opc = ISD::INTRINSIC_VOID;
5629     Info.ptrVal = I.getArgOperand(0);
5630     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
5631     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
5632     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
5633       ScalarVT = MVT::i8;
5634     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
5635       ScalarVT = MVT::i16;
5636     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
5637       ScalarVT = MVT::i32;
5638 
5639     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
5640     Info.align = Align(1);
5641     Info.flags |= MachineMemOperand::MOStore;
5642     break;
5643   }
5644   case GATHER:
5645   case GATHER_AVX2: {
5646     Info.opc = ISD::INTRINSIC_W_CHAIN;
5647     Info.ptrVal = nullptr;
5648     MVT DataVT = MVT::getVT(I.getType());
5649     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5650     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5651                                 IndexVT.getVectorNumElements());
5652     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5653     Info.align = Align(1);
5654     Info.flags |= MachineMemOperand::MOLoad;
5655     break;
5656   }
5657   case SCATTER: {
5658     Info.opc = ISD::INTRINSIC_VOID;
5659     Info.ptrVal = nullptr;
5660     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
5661     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5662     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5663                                 IndexVT.getVectorNumElements());
5664     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5665     Info.align = Align(1);
5666     Info.flags |= MachineMemOperand::MOStore;
5667     break;
5668   }
5669   default:
5670     return false;
5671   }
5672 
5673   return true;
5674 }
5675 
5676 /// Returns true if the target can instruction select the
5677 /// specified FP immediate natively. If false, the legalizer will
5678 /// materialize the FP immediate as a load from a constant pool.
5679 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5680                                      bool ForCodeSize) const {
5681   for (const APFloat &FPImm : LegalFPImmediates)
5682     if (Imm.bitwiseIsEqual(FPImm))
5683       return true;
5684   return false;
5685 }
5686 
5687 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5688                                               ISD::LoadExtType ExtTy,
5689                                               EVT NewVT) const {
5690   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
5691 
5692   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5693   // relocation target a movq or addq instruction: don't let the load shrink.
5694   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5695   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5696     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5697       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5698 
5699   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5700   // those uses are extracted directly into a store, then the extract + store
5701   // can be store-folded. Therefore, it's probably not worth splitting the load.
5702   EVT VT = Load->getValueType(0);
5703   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5704     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5705       // Skip uses of the chain value. Result 0 of the node is the load value.
5706       if (UI.getUse().getResNo() != 0)
5707         continue;
5708 
5709       // If this use is not an extract + store, it's probably worth splitting.
5710       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5711           UI->use_begin()->getOpcode() != ISD::STORE)
5712         return true;
5713     }
5714     // All non-chain uses are extract + store.
5715     return false;
5716   }
5717 
5718   return true;
5719 }
5720 
5721 /// Returns true if it is beneficial to convert a load of a constant
5722 /// to just the constant itself.
5723 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5724                                                           Type *Ty) const {
5725   assert(Ty->isIntegerTy());
5726 
5727   unsigned BitSize = Ty->getPrimitiveSizeInBits();
5728   if (BitSize == 0 || BitSize > 64)
5729     return false;
5730   return true;
5731 }
5732 
5733 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5734   // If we are using XMM registers in the ABI and the condition of the select is
5735   // a floating-point compare and we have blendv or conditional move, then it is
5736   // cheaper to select instead of doing a cross-register move and creating a
5737   // load that depends on the compare result.
5738   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5739   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5740 }
5741 
5742 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5743   // TODO: It might be a win to ease or lift this restriction, but the generic
5744   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5745   if (VT.isVector() && Subtarget.hasAVX512())
5746     return false;
5747 
5748   return true;
5749 }
5750 
5751 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5752                                                SDValue C) const {
5753   // TODO: We handle scalars using custom code, but generic combining could make
5754   // that unnecessary.
5755   APInt MulC;
5756   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5757     return false;
5758 
5759   // Find the type this will be legalized too. Otherwise we might prematurely
5760   // convert this to shl+add/sub and then still have to type legalize those ops.
5761   // Another choice would be to defer the decision for illegal types until
5762   // after type legalization. But constant splat vectors of i64 can't make it
5763   // through type legalization on 32-bit targets so we would need to special
5764   // case vXi64.
5765   while (getTypeAction(Context, VT) != TypeLegal)
5766     VT = getTypeToTransformTo(Context, VT);
5767 
5768   // If vector multiply is legal, assume that's faster than shl + add/sub.
5769   // Multiply is a complex op with higher latency and lower throughput in
5770   // most implementations, sub-vXi32 vector multiplies are always fast,
5771   // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
5772   // is always going to be slow.
5773   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5774   if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
5775       (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
5776     return false;
5777 
5778   // shl+add, shl+sub, shl+add+neg
5779   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
5780          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
5781 }
5782 
5783 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
5784                                                 unsigned Index) const {
5785   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
5786     return false;
5787 
5788   // Mask vectors support all subregister combinations and operations that
5789   // extract half of vector.
5790   if (ResVT.getVectorElementType() == MVT::i1)
5791     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
5792                           (Index == ResVT.getVectorNumElements()));
5793 
5794   return (Index % ResVT.getVectorNumElements()) == 0;
5795 }
5796 
5797 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
5798   unsigned Opc = VecOp.getOpcode();
5799 
5800   // Assume target opcodes can't be scalarized.
5801   // TODO - do we have any exceptions?
5802   if (Opc >= ISD::BUILTIN_OP_END)
5803     return false;
5804 
5805   // If the vector op is not supported, try to convert to scalar.
5806   EVT VecVT = VecOp.getValueType();
5807   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
5808     return true;
5809 
5810   // If the vector op is supported, but the scalar op is not, the transform may
5811   // not be worthwhile.
5812   EVT ScalarVT = VecVT.getScalarType();
5813   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
5814 }
5815 
5816 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
5817                                              bool) const {
5818   // TODO: Allow vectors?
5819   if (VT.isVector())
5820     return false;
5821   return VT.isSimple() || !isOperationExpand(Opcode, VT);
5822 }
5823 
5824 bool X86TargetLowering::isCheapToSpeculateCttz() const {
5825   // Speculate cttz only if we can directly use TZCNT.
5826   return Subtarget.hasBMI();
5827 }
5828 
5829 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5830   // Speculate ctlz only if we can directly use LZCNT.
5831   return Subtarget.hasLZCNT();
5832 }
5833 
5834 bool X86TargetLowering::hasBitPreservingFPLogic(EVT VT) const {
5835   return VT == MVT::f32 || VT == MVT::f64 || VT.isVector();
5836 }
5837 
5838 bool X86TargetLowering::ShouldShrinkFPConstant(EVT VT) const {
5839   // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
5840   // expensive than a straight movsd. On the other hand, it's important to
5841   // shrink long double fp constant since fldt is very slow.
5842   return !Subtarget.hasSSE2() || VT == MVT::f80;
5843 }
5844 
5845 bool X86TargetLowering::isScalarFPTypeInSSEReg(EVT VT) const {
5846   return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
5847          (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
5848 }
5849 
5850 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5851                                                 const SelectionDAG &DAG,
5852                                                 const MachineMemOperand &MMO) const {
5853   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5854       BitcastVT.getVectorElementType() == MVT::i1)
5855     return false;
5856 
5857   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5858     return false;
5859 
5860   // If both types are legal vectors, it's always ok to convert them.
5861   if (LoadVT.isVector() && BitcastVT.isVector() &&
5862       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5863     return true;
5864 
5865   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5866 }
5867 
5868 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5869                                          const MachineFunction &MF) const {
5870   // Do not merge to float value size (128 bytes) if no implicit
5871   // float attribute is set.
5872   bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
5873 
5874   if (NoFloat) {
5875     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5876     return (MemVT.getSizeInBits() <= MaxIntSize);
5877   }
5878   // Make sure we don't merge greater than our preferred vector
5879   // width.
5880   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5881     return false;
5882 
5883   return true;
5884 }
5885 
5886 bool X86TargetLowering::isCtlzFast() const {
5887   return Subtarget.hasFastLZCNT();
5888 }
5889 
5890 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5891     const Instruction &AndI) const {
5892   return true;
5893 }
5894 
5895 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5896   EVT VT = Y.getValueType();
5897 
5898   if (VT.isVector())
5899     return false;
5900 
5901   if (!Subtarget.hasBMI())
5902     return false;
5903 
5904   // There are only 32-bit and 64-bit forms for 'andn'.
5905   if (VT != MVT::i32 && VT != MVT::i64)
5906     return false;
5907 
5908   return !isa<ConstantSDNode>(Y);
5909 }
5910 
5911 bool X86TargetLowering::hasAndNot(SDValue Y) const {
5912   EVT VT = Y.getValueType();
5913 
5914   if (!VT.isVector())
5915     return hasAndNotCompare(Y);
5916 
5917   // Vector.
5918 
5919   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5920     return false;
5921 
5922   if (VT == MVT::v4i32)
5923     return true;
5924 
5925   return Subtarget.hasSSE2();
5926 }
5927 
5928 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5929   return X.getValueType().isScalarInteger(); // 'bt'
5930 }
5931 
5932 bool X86TargetLowering::
5933     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5934         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5935         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5936         SelectionDAG &DAG) const {
5937   // Does baseline recommend not to perform the fold by default?
5938   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5939           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5940     return false;
5941   // For scalars this transform is always beneficial.
5942   if (X.getValueType().isScalarInteger())
5943     return true;
5944   // If all the shift amounts are identical, then transform is beneficial even
5945   // with rudimentary SSE2 shifts.
5946   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5947     return true;
5948   // If we have AVX2 with it's powerful shift operations, then it's also good.
5949   if (Subtarget.hasAVX2())
5950     return true;
5951   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5952   return NewShiftOpcode == ISD::SHL;
5953 }
5954 
5955 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5956     const SDNode *N, CombineLevel Level) const {
5957   assert(((N->getOpcode() == ISD::SHL &&
5958            N->getOperand(0).getOpcode() == ISD::SRL) ||
5959           (N->getOpcode() == ISD::SRL &&
5960            N->getOperand(0).getOpcode() == ISD::SHL)) &&
5961          "Expected shift-shift mask");
5962   // TODO: Should we always create i64 masks? Or only folded immediates?
5963   EVT VT = N->getValueType(0);
5964   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5965       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5966     // Only fold if the shift values are equal - so it folds to AND.
5967     // TODO - we should fold if either is a non-uniform vector but we don't do
5968     // the fold for non-splats yet.
5969     return N->getOperand(1) == N->getOperand(0).getOperand(1);
5970   }
5971   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5972 }
5973 
5974 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5975   EVT VT = Y.getValueType();
5976 
5977   // For vectors, we don't have a preference, but we probably want a mask.
5978   if (VT.isVector())
5979     return false;
5980 
5981   // 64-bit shifts on 32-bit targets produce really bad bloated code.
5982   if (VT == MVT::i64 && !Subtarget.is64Bit())
5983     return false;
5984 
5985   return true;
5986 }
5987 
5988 bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5989                                           SDNode *N) const {
5990   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5991       !Subtarget.isOSWindows())
5992     return false;
5993   return true;
5994 }
5995 
5996 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5997   // Any legal vector type can be splatted more efficiently than
5998   // loading/spilling from memory.
5999   return isTypeLegal(VT);
6000 }
6001 
6002 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
6003   MVT VT = MVT::getIntegerVT(NumBits);
6004   if (isTypeLegal(VT))
6005     return VT;
6006 
6007   // PMOVMSKB can handle this.
6008   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
6009     return MVT::v16i8;
6010 
6011   // VPMOVMSKB can handle this.
6012   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
6013     return MVT::v32i8;
6014 
6015   // TODO: Allow 64-bit type for 32-bit target.
6016   // TODO: 512-bit types should be allowed, but make sure that those
6017   // cases are handled in combineVectorSizedSetCCEquality().
6018 
6019   return MVT::INVALID_SIMPLE_VALUE_TYPE;
6020 }
6021 
6022 /// Val is the undef sentinel value or equal to the specified value.
6023 static bool isUndefOrEqual(int Val, int CmpVal) {
6024   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
6025 }
6026 
6027 /// Return true if every element in Mask is the undef sentinel value or equal to
6028 /// the specified value..
6029 static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
6030   return llvm::all_of(Mask, [CmpVal](int M) {
6031     return (M == SM_SentinelUndef) || (M == CmpVal);
6032   });
6033 }
6034 
6035 /// Val is either the undef or zero sentinel value.
6036 static bool isUndefOrZero(int Val) {
6037   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
6038 }
6039 
6040 /// Return true if every element in Mask, beginning from position Pos and ending
6041 /// in Pos+Size is the undef sentinel value.
6042 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
6043   return llvm::all_of(Mask.slice(Pos, Size),
6044                       [](int M) { return M == SM_SentinelUndef; });
6045 }
6046 
6047 /// Return true if the mask creates a vector whose lower half is undefined.
6048 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
6049   unsigned NumElts = Mask.size();
6050   return isUndefInRange(Mask, 0, NumElts / 2);
6051 }
6052 
6053 /// Return true if the mask creates a vector whose upper half is undefined.
6054 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
6055   unsigned NumElts = Mask.size();
6056   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
6057 }
6058 
6059 /// Return true if Val falls within the specified range (L, H].
6060 static bool isInRange(int Val, int Low, int Hi) {
6061   return (Val >= Low && Val < Hi);
6062 }
6063 
6064 /// Return true if the value of any element in Mask falls within the specified
6065 /// range (L, H].
6066 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
6067   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
6068 }
6069 
6070 /// Return true if the value of any element in Mask is the zero sentinel value.
6071 static bool isAnyZero(ArrayRef<int> Mask) {
6072   return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
6073 }
6074 
6075 /// Return true if the value of any element in Mask is the zero or undef
6076 /// sentinel values.
6077 static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
6078   return llvm::any_of(Mask, [](int M) {
6079     return M == SM_SentinelZero || M == SM_SentinelUndef;
6080   });
6081 }
6082 
6083 /// Return true if Val is undef or if its value falls within the
6084 /// specified range (L, H].
6085 static bool isUndefOrInRange(int Val, int Low, int Hi) {
6086   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
6087 }
6088 
6089 /// Return true if every element in Mask is undef or if its value
6090 /// falls within the specified range (L, H].
6091 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
6092   return llvm::all_of(
6093       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
6094 }
6095 
6096 /// Return true if Val is undef, zero or if its value falls within the
6097 /// specified range (L, H].
6098 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
6099   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
6100 }
6101 
6102 /// Return true if every element in Mask is undef, zero or if its value
6103 /// falls within the specified range (L, H].
6104 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
6105   return llvm::all_of(
6106       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
6107 }
6108 
6109 /// Return true if every element in Mask, beginning
6110 /// from position Pos and ending in Pos + Size, falls within the specified
6111 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
6112 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
6113                                        unsigned Size, int Low, int Step = 1) {
6114   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
6115     if (!isUndefOrEqual(Mask[i], Low))
6116       return false;
6117   return true;
6118 }
6119 
6120 /// Return true if every element in Mask, beginning
6121 /// from position Pos and ending in Pos+Size, falls within the specified
6122 /// sequential range (Low, Low+Size], or is undef or is zero.
6123 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
6124                                              unsigned Size, int Low,
6125                                              int Step = 1) {
6126   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
6127     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
6128       return false;
6129   return true;
6130 }
6131 
6132 /// Return true if every element in Mask, beginning
6133 /// from position Pos and ending in Pos+Size is undef or is zero.
6134 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
6135                                  unsigned Size) {
6136   return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
6137 }
6138 
6139 /// Helper function to test whether a shuffle mask could be
6140 /// simplified by widening the elements being shuffled.
6141 ///
6142 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
6143 /// leaves it in an unspecified state.
6144 ///
6145 /// NOTE: This must handle normal vector shuffle masks and *target* vector
6146 /// shuffle masks. The latter have the special property of a '-2' representing
6147 /// a zero-ed lane of a vector.
6148 static bool canWidenShuffleElements(ArrayRef<int> Mask,
6149                                     SmallVectorImpl<int> &WidenedMask) {
6150   WidenedMask.assign(Mask.size() / 2, 0);
6151   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
6152     int M0 = Mask[i];
6153     int M1 = Mask[i + 1];
6154 
6155     // If both elements are undef, its trivial.
6156     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
6157       WidenedMask[i / 2] = SM_SentinelUndef;
6158       continue;
6159     }
6160 
6161     // Check for an undef mask and a mask value properly aligned to fit with
6162     // a pair of values. If we find such a case, use the non-undef mask's value.
6163     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
6164       WidenedMask[i / 2] = M1 / 2;
6165       continue;
6166     }
6167     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
6168       WidenedMask[i / 2] = M0 / 2;
6169       continue;
6170     }
6171 
6172     // When zeroing, we need to spread the zeroing across both lanes to widen.
6173     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
6174       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
6175           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
6176         WidenedMask[i / 2] = SM_SentinelZero;
6177         continue;
6178       }
6179       return false;
6180     }
6181 
6182     // Finally check if the two mask values are adjacent and aligned with
6183     // a pair.
6184     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
6185       WidenedMask[i / 2] = M0 / 2;
6186       continue;
6187     }
6188 
6189     // Otherwise we can't safely widen the elements used in this shuffle.
6190     return false;
6191   }
6192   assert(WidenedMask.size() == Mask.size() / 2 &&
6193          "Incorrect size of mask after widening the elements!");
6194 
6195   return true;
6196 }
6197 
6198 static bool canWidenShuffleElements(ArrayRef<int> Mask,
6199                                     const APInt &Zeroable,
6200                                     bool V2IsZero,
6201                                     SmallVectorImpl<int> &WidenedMask) {
6202   // Create an alternative mask with info about zeroable elements.
6203   // Here we do not set undef elements as zeroable.
6204   SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
6205   if (V2IsZero) {
6206     assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
6207     for (int i = 0, Size = Mask.size(); i != Size; ++i)
6208       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
6209         ZeroableMask[i] = SM_SentinelZero;
6210   }
6211   return canWidenShuffleElements(ZeroableMask, WidenedMask);
6212 }
6213 
6214 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
6215   SmallVector<int, 32> WidenedMask;
6216   return canWidenShuffleElements(Mask, WidenedMask);
6217 }
6218 
6219 // Attempt to narrow/widen shuffle mask until it matches the target number of
6220 // elements.
6221 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
6222                                  SmallVectorImpl<int> &ScaledMask) {
6223   unsigned NumSrcElts = Mask.size();
6224   assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
6225          "Illegal shuffle scale factor");
6226 
6227   // Narrowing is guaranteed to work.
6228   if (NumDstElts >= NumSrcElts) {
6229     int Scale = NumDstElts / NumSrcElts;
6230     llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
6231     return true;
6232   }
6233 
6234   // We have to repeat the widening until we reach the target size, but we can
6235   // split out the first widening as it sets up ScaledMask for us.
6236   if (canWidenShuffleElements(Mask, ScaledMask)) {
6237     while (ScaledMask.size() > NumDstElts) {
6238       SmallVector<int, 16> WidenedMask;
6239       if (!canWidenShuffleElements(ScaledMask, WidenedMask))
6240         return false;
6241       ScaledMask = std::move(WidenedMask);
6242     }
6243     return true;
6244   }
6245 
6246   return false;
6247 }
6248 
6249 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
6250 bool X86::isZeroNode(SDValue Elt) {
6251   return isNullConstant(Elt) || isNullFPConstant(Elt);
6252 }
6253 
6254 // Build a vector of constants.
6255 // Use an UNDEF node if MaskElt == -1.
6256 // Split 64-bit constants in the 32-bit mode.
6257 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
6258                               const SDLoc &dl, bool IsMask = false) {
6259 
6260   SmallVector<SDValue, 32>  Ops;
6261   bool Split = false;
6262 
6263   MVT ConstVecVT = VT;
6264   unsigned NumElts = VT.getVectorNumElements();
6265   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
6266   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
6267     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
6268     Split = true;
6269   }
6270 
6271   MVT EltVT = ConstVecVT.getVectorElementType();
6272   for (unsigned i = 0; i < NumElts; ++i) {
6273     bool IsUndef = Values[i] < 0 && IsMask;
6274     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
6275       DAG.getConstant(Values[i], dl, EltVT);
6276     Ops.push_back(OpNode);
6277     if (Split)
6278       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
6279                     DAG.getConstant(0, dl, EltVT));
6280   }
6281   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
6282   if (Split)
6283     ConstsNode = DAG.getBitcast(VT, ConstsNode);
6284   return ConstsNode;
6285 }
6286 
6287 static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
6288                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6289   assert(Bits.size() == Undefs.getBitWidth() &&
6290          "Unequal constant and undef arrays");
6291   SmallVector<SDValue, 32> Ops;
6292   bool Split = false;
6293 
6294   MVT ConstVecVT = VT;
6295   unsigned NumElts = VT.getVectorNumElements();
6296   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
6297   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
6298     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
6299     Split = true;
6300   }
6301 
6302   MVT EltVT = ConstVecVT.getVectorElementType();
6303   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
6304     if (Undefs[i]) {
6305       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
6306       continue;
6307     }
6308     const APInt &V = Bits[i];
6309     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
6310     if (Split) {
6311       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
6312       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
6313     } else if (EltVT == MVT::f32) {
6314       APFloat FV(APFloat::IEEEsingle(), V);
6315       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
6316     } else if (EltVT == MVT::f64) {
6317       APFloat FV(APFloat::IEEEdouble(), V);
6318       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
6319     } else {
6320       Ops.push_back(DAG.getConstant(V, dl, EltVT));
6321     }
6322   }
6323 
6324   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
6325   return DAG.getBitcast(VT, ConstsNode);
6326 }
6327 
6328 /// Returns a vector of specified type with all zero elements.
6329 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
6330                              SelectionDAG &DAG, const SDLoc &dl) {
6331   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
6332           VT.getVectorElementType() == MVT::i1) &&
6333          "Unexpected vector type");
6334 
6335   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
6336   // type. This ensures they get CSE'd. But if the integer type is not
6337   // available, use a floating-point +0.0 instead.
6338   SDValue Vec;
6339   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
6340     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
6341   } else if (VT.isFloatingPoint()) {
6342     Vec = DAG.getConstantFP(+0.0, dl, VT);
6343   } else if (VT.getVectorElementType() == MVT::i1) {
6344     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
6345            "Unexpected vector type");
6346     Vec = DAG.getConstant(0, dl, VT);
6347   } else {
6348     unsigned Num32BitElts = VT.getSizeInBits() / 32;
6349     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
6350   }
6351   return DAG.getBitcast(VT, Vec);
6352 }
6353 
6354 // Helper to determine if the ops are all the extracted subvectors come from a
6355 // single source. If we allow commute they don't have to be in order (Lo/Hi).
6356 static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
6357   if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6358       RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6359       LHS.getValueType() != RHS.getValueType() ||
6360       LHS.getOperand(0) != RHS.getOperand(0))
6361     return SDValue();
6362 
6363   SDValue Src = LHS.getOperand(0);
6364   if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
6365     return SDValue();
6366 
6367   unsigned NumElts = LHS.getValueType().getVectorNumElements();
6368   if ((LHS.getConstantOperandAPInt(1) == 0 &&
6369        RHS.getConstantOperandAPInt(1) == NumElts) ||
6370       (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
6371        LHS.getConstantOperandAPInt(1) == NumElts))
6372     return Src;
6373 
6374   return SDValue();
6375 }
6376 
6377 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
6378                                 const SDLoc &dl, unsigned vectorWidth) {
6379   EVT VT = Vec.getValueType();
6380   EVT ElVT = VT.getVectorElementType();
6381   unsigned Factor = VT.getSizeInBits() / vectorWidth;
6382   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
6383                                   VT.getVectorNumElements() / Factor);
6384 
6385   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
6386   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
6387   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
6388 
6389   // This is the index of the first element of the vectorWidth-bit chunk
6390   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
6391   IdxVal &= ~(ElemsPerChunk - 1);
6392 
6393   // If the input is a buildvector just emit a smaller one.
6394   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
6395     return DAG.getBuildVector(ResultVT, dl,
6396                               Vec->ops().slice(IdxVal, ElemsPerChunk));
6397 
6398   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
6399   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
6400 }
6401 
6402 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
6403 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
6404 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
6405 /// instructions or a simple subregister reference. Idx is an index in the
6406 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
6407 /// lowering EXTRACT_VECTOR_ELT operations easier.
6408 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
6409                                    SelectionDAG &DAG, const SDLoc &dl) {
6410   assert((Vec.getValueType().is256BitVector() ||
6411           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
6412   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
6413 }
6414 
6415 /// Generate a DAG to grab 256-bits from a 512-bit vector.
6416 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
6417                                    SelectionDAG &DAG, const SDLoc &dl) {
6418   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
6419   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
6420 }
6421 
6422 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
6423                                SelectionDAG &DAG, const SDLoc &dl,
6424                                unsigned vectorWidth) {
6425   assert((vectorWidth == 128 || vectorWidth == 256) &&
6426          "Unsupported vector width");
6427   // Inserting UNDEF is Result
6428   if (Vec.isUndef())
6429     return Result;
6430   EVT VT = Vec.getValueType();
6431   EVT ElVT = VT.getVectorElementType();
6432   EVT ResultVT = Result.getValueType();
6433 
6434   // Insert the relevant vectorWidth bits.
6435   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
6436   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
6437 
6438   // This is the index of the first element of the vectorWidth-bit chunk
6439   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
6440   IdxVal &= ~(ElemsPerChunk - 1);
6441 
6442   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
6443   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
6444 }
6445 
6446 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
6447 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
6448 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
6449 /// simple superregister reference.  Idx is an index in the 128 bits
6450 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
6451 /// lowering INSERT_VECTOR_ELT operations easier.
6452 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
6453                                   SelectionDAG &DAG, const SDLoc &dl) {
6454   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
6455   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
6456 }
6457 
6458 /// Widen a vector to a larger size with the same scalar type, with the new
6459 /// elements either zero or undef.
6460 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
6461                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
6462                               const SDLoc &dl) {
6463   assert(Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() &&
6464          Vec.getValueType().getScalarType() == VT.getScalarType() &&
6465          "Unsupported vector widening type");
6466   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
6467                                 : DAG.getUNDEF(VT);
6468   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
6469                      DAG.getIntPtrConstant(0, dl));
6470 }
6471 
6472 /// Widen a vector to a larger size with the same scalar type, with the new
6473 /// elements either zero or undef.
6474 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
6475                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
6476                               const SDLoc &dl, unsigned WideSizeInBits) {
6477   assert(Vec.getValueSizeInBits() < WideSizeInBits &&
6478          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
6479          "Unsupported vector widening type");
6480   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
6481   MVT SVT = Vec.getSimpleValueType().getScalarType();
6482   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
6483   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
6484 }
6485 
6486 // Helper function to collect subvector ops that are concatenated together,
6487 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
6488 // The subvectors in Ops are guaranteed to be the same type.
6489 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops,
6490                              SelectionDAG &DAG) {
6491   assert(Ops.empty() && "Expected an empty ops vector");
6492 
6493   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
6494     Ops.append(N->op_begin(), N->op_end());
6495     return true;
6496   }
6497 
6498   if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
6499     SDValue Src = N->getOperand(0);
6500     SDValue Sub = N->getOperand(1);
6501     const APInt &Idx = N->getConstantOperandAPInt(2);
6502     EVT VT = Src.getValueType();
6503     EVT SubVT = Sub.getValueType();
6504 
6505     // TODO - Handle more general insert_subvector chains.
6506     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
6507       // insert_subvector(undef, x, lo)
6508       if (Idx == 0 && Src.isUndef()) {
6509         Ops.push_back(Sub);
6510         Ops.push_back(DAG.getUNDEF(SubVT));
6511         return true;
6512       }
6513       if (Idx == (VT.getVectorNumElements() / 2)) {
6514         // insert_subvector(insert_subvector(undef, x, lo), y, hi)
6515         if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6516             Src.getOperand(1).getValueType() == SubVT &&
6517             isNullConstant(Src.getOperand(2))) {
6518           Ops.push_back(Src.getOperand(1));
6519           Ops.push_back(Sub);
6520           return true;
6521         }
6522         // insert_subvector(x, extract_subvector(x, lo), hi)
6523         if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6524             Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
6525           Ops.append(2, Sub);
6526           return true;
6527         }
6528         // insert_subvector(undef, x, hi)
6529         if (Src.isUndef()) {
6530           Ops.push_back(DAG.getUNDEF(SubVT));
6531           Ops.push_back(Sub);
6532           return true;
6533         }
6534       }
6535     }
6536   }
6537 
6538   return false;
6539 }
6540 
6541 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
6542                                                const SDLoc &dl) {
6543   EVT VT = Op.getValueType();
6544   unsigned NumElems = VT.getVectorNumElements();
6545   unsigned SizeInBits = VT.getSizeInBits();
6546   assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
6547          "Can't split odd sized vector");
6548 
6549   // If this is a splat value (with no-undefs) then use the lower subvector,
6550   // which should be a free extraction.
6551   SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
6552   if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
6553     return std::make_pair(Lo, Lo);
6554 
6555   SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
6556   return std::make_pair(Lo, Hi);
6557 }
6558 
6559 /// Break an operation into 2 half sized ops and then concatenate the results.
6560 static SDValue splitVectorOp(SDValue Op, SelectionDAG &DAG) {
6561   unsigned NumOps = Op.getNumOperands();
6562   EVT VT = Op.getValueType();
6563   SDLoc dl(Op);
6564 
6565   // Extract the LHS Lo/Hi vectors
6566   SmallVector<SDValue> LoOps(NumOps, SDValue());
6567   SmallVector<SDValue> HiOps(NumOps, SDValue());
6568   for (unsigned I = 0; I != NumOps; ++I) {
6569     SDValue SrcOp = Op.getOperand(I);
6570     if (!SrcOp.getValueType().isVector()) {
6571       LoOps[I] = HiOps[I] = SrcOp;
6572       continue;
6573     }
6574     std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
6575   }
6576 
6577   EVT LoVT, HiVT;
6578   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6579   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6580                      DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
6581                      DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
6582 }
6583 
6584 /// Break an unary integer operation into 2 half sized ops and then
6585 /// concatenate the result back.
6586 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
6587   // Make sure we only try to split 256/512-bit types to avoid creating
6588   // narrow vectors.
6589   EVT VT = Op.getValueType();
6590   (void)VT;
6591   assert((Op.getOperand(0).getValueType().is256BitVector() ||
6592           Op.getOperand(0).getValueType().is512BitVector()) &&
6593          (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6594   assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
6595              VT.getVectorNumElements() &&
6596          "Unexpected VTs!");
6597   return splitVectorOp(Op, DAG);
6598 }
6599 
6600 /// Break a binary integer operation into 2 half sized ops and then
6601 /// concatenate the result back.
6602 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
6603   // Assert that all the types match.
6604   EVT VT = Op.getValueType();
6605   (void)VT;
6606   assert(Op.getOperand(0).getValueType() == VT &&
6607          Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
6608   assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6609   return splitVectorOp(Op, DAG);
6610 }
6611 
6612 // Helper for splitting operands of an operation to legal target size and
6613 // apply a function on each part.
6614 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
6615 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
6616 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
6617 // The argument Builder is a function that will be applied on each split part:
6618 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
6619 template <typename F>
6620 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
6621                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
6622                          F Builder, bool CheckBWI = true) {
6623   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
6624   unsigned NumSubs = 1;
6625   if ((CheckBWI && Subtarget.useBWIRegs()) ||
6626       (!CheckBWI && Subtarget.useAVX512Regs())) {
6627     if (VT.getSizeInBits() > 512) {
6628       NumSubs = VT.getSizeInBits() / 512;
6629       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
6630     }
6631   } else if (Subtarget.hasAVX2()) {
6632     if (VT.getSizeInBits() > 256) {
6633       NumSubs = VT.getSizeInBits() / 256;
6634       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
6635     }
6636   } else {
6637     if (VT.getSizeInBits() > 128) {
6638       NumSubs = VT.getSizeInBits() / 128;
6639       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
6640     }
6641   }
6642 
6643   if (NumSubs == 1)
6644     return Builder(DAG, DL, Ops);
6645 
6646   SmallVector<SDValue, 4> Subs;
6647   for (unsigned i = 0; i != NumSubs; ++i) {
6648     SmallVector<SDValue, 2> SubOps;
6649     for (SDValue Op : Ops) {
6650       EVT OpVT = Op.getValueType();
6651       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
6652       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
6653       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
6654     }
6655     Subs.push_back(Builder(DAG, DL, SubOps));
6656   }
6657   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
6658 }
6659 
6660 // Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
6661 // targets.
6662 static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
6663                              ArrayRef<SDValue> Ops, SelectionDAG &DAG,
6664                              const X86Subtarget &Subtarget) {
6665   assert(Subtarget.hasAVX512() && "AVX512 target expected");
6666   MVT SVT = VT.getScalarType();
6667 
6668   // If we have a 32/64 splatted constant, splat it to DstTy to
6669   // encourage a foldable broadcast'd operand.
6670   auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
6671     unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
6672     // AVX512 broadcasts 32/64-bit operands.
6673     // TODO: Support float once getAVX512Node is used by fp-ops.
6674     if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
6675         !DAG.getTargetLoweringInfo().isTypeLegal(SVT))
6676       return SDValue();
6677     // If we're not widening, don't bother if we're not bitcasting.
6678     if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
6679       return SDValue();
6680     if (auto *BV = dyn_cast<BuildVectorSDNode>(peekThroughBitcasts(Op))) {
6681       APInt SplatValue, SplatUndef;
6682       unsigned SplatBitSize;
6683       bool HasAnyUndefs;
6684       if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6685                               HasAnyUndefs, OpEltSizeInBits) &&
6686           !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
6687         return DAG.getConstant(SplatValue, DL, DstVT);
6688     }
6689     return SDValue();
6690   };
6691 
6692   bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
6693 
6694   MVT DstVT = VT;
6695   if (Widen)
6696     DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
6697 
6698   // Canonicalize src operands.
6699   SmallVector<SDValue> SrcOps(Ops.begin(), Ops.end());
6700   for (SDValue &Op : SrcOps) {
6701     MVT OpVT = Op.getSimpleValueType();
6702     // Just pass through scalar operands.
6703     if (!OpVT.isVector())
6704       continue;
6705     assert(OpVT == VT && "Vector type mismatch");
6706 
6707     if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
6708       Op = BroadcastOp;
6709       continue;
6710     }
6711 
6712     // Just widen the subvector by inserting into an undef wide vector.
6713     if (Widen)
6714       Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
6715   }
6716 
6717   SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
6718 
6719   // Perform the 512-bit op then extract the bottom subvector.
6720   if (Widen)
6721     Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
6722   return Res;
6723 }
6724 
6725 /// Insert i1-subvector to i1-vector.
6726 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
6727                                 const X86Subtarget &Subtarget) {
6728 
6729   SDLoc dl(Op);
6730   SDValue Vec = Op.getOperand(0);
6731   SDValue SubVec = Op.getOperand(1);
6732   SDValue Idx = Op.getOperand(2);
6733   unsigned IdxVal = Op.getConstantOperandVal(2);
6734 
6735   // Inserting undef is a nop. We can just return the original vector.
6736   if (SubVec.isUndef())
6737     return Vec;
6738 
6739   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
6740     return Op;
6741 
6742   MVT OpVT = Op.getSimpleValueType();
6743   unsigned NumElems = OpVT.getVectorNumElements();
6744   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6745 
6746   // Extend to natively supported kshift.
6747   MVT WideOpVT = OpVT;
6748   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
6749     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
6750 
6751   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
6752   // if necessary.
6753   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
6754     // May need to promote to a legal type.
6755     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6756                      DAG.getConstant(0, dl, WideOpVT),
6757                      SubVec, Idx);
6758     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6759   }
6760 
6761   MVT SubVecVT = SubVec.getSimpleValueType();
6762   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
6763   assert(IdxVal + SubVecNumElems <= NumElems &&
6764          IdxVal % SubVecVT.getSizeInBits() == 0 &&
6765          "Unexpected index value in INSERT_SUBVECTOR");
6766 
6767   SDValue Undef = DAG.getUNDEF(WideOpVT);
6768 
6769   if (IdxVal == 0) {
6770     // Zero lower bits of the Vec
6771     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
6772     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
6773                       ZeroIdx);
6774     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6775     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6776     // Merge them together, SubVec should be zero extended.
6777     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6778                          DAG.getConstant(0, dl, WideOpVT),
6779                          SubVec, ZeroIdx);
6780     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6781     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6782   }
6783 
6784   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6785                        Undef, SubVec, ZeroIdx);
6786 
6787   if (Vec.isUndef()) {
6788     assert(IdxVal != 0 && "Unexpected index");
6789     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6790                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6791     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6792   }
6793 
6794   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
6795     assert(IdxVal != 0 && "Unexpected index");
6796     // If upper elements of Vec are known undef, then just shift into place.
6797     if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
6798                      [](SDValue V) { return V.isUndef(); })) {
6799       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6800                            DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6801     } else {
6802       NumElems = WideOpVT.getVectorNumElements();
6803       unsigned ShiftLeft = NumElems - SubVecNumElems;
6804       unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6805       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6806                            DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6807       if (ShiftRight != 0)
6808         SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6809                              DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6810     }
6811     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6812   }
6813 
6814   // Simple case when we put subvector in the upper part
6815   if (IdxVal + SubVecNumElems == NumElems) {
6816     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6817                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6818     if (SubVecNumElems * 2 == NumElems) {
6819       // Special case, use legal zero extending insert_subvector. This allows
6820       // isel to optimize when bits are known zero.
6821       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
6822       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6823                         DAG.getConstant(0, dl, WideOpVT),
6824                         Vec, ZeroIdx);
6825     } else {
6826       // Otherwise use explicit shifts to zero the bits.
6827       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6828                         Undef, Vec, ZeroIdx);
6829       NumElems = WideOpVT.getVectorNumElements();
6830       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
6831       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6832       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6833     }
6834     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6835     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6836   }
6837 
6838   // Inserting into the middle is more complicated.
6839 
6840   NumElems = WideOpVT.getVectorNumElements();
6841 
6842   // Widen the vector if needed.
6843   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
6844 
6845   unsigned ShiftLeft = NumElems - SubVecNumElems;
6846   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6847 
6848   // Do an optimization for the the most frequently used types.
6849   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
6850     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
6851     Mask0.flipAllBits();
6852     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
6853     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
6854     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
6855     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6856                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6857     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6858                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6859     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6860 
6861     // Reduce to original width if needed.
6862     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6863   }
6864 
6865   // Clear the upper bits of the subvector and move it to its insert position.
6866   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6867                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6868   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6869                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6870 
6871   // Isolate the bits below the insertion point.
6872   unsigned LowShift = NumElems - IdxVal;
6873   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
6874                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
6875   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
6876                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
6877 
6878   // Isolate the bits after the last inserted bit.
6879   unsigned HighShift = IdxVal + SubVecNumElems;
6880   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
6881                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
6882   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
6883                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
6884 
6885   // Now OR all 3 pieces together.
6886   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
6887   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
6888 
6889   // Reduce to original width if needed.
6890   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6891 }
6892 
6893 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
6894                                 const SDLoc &dl) {
6895   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
6896   EVT SubVT = V1.getValueType();
6897   EVT SubSVT = SubVT.getScalarType();
6898   unsigned SubNumElts = SubVT.getVectorNumElements();
6899   unsigned SubVectorWidth = SubVT.getSizeInBits();
6900   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
6901   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
6902   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
6903 }
6904 
6905 /// Returns a vector of specified type with all bits set.
6906 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
6907 /// Then bitcast to their original type, ensuring they get CSE'd.
6908 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6909   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6910          "Expected a 128/256/512-bit vector type");
6911 
6912   APInt Ones = APInt::getAllOnes(32);
6913   unsigned NumElts = VT.getSizeInBits() / 32;
6914   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
6915   return DAG.getBitcast(VT, Vec);
6916 }
6917 
6918 // Convert *_EXTEND_VECTOR_INREG to *_EXTEND opcode.
6919 static unsigned getOpcode_EXTEND(unsigned Opcode) {
6920   switch (Opcode) {
6921   case ISD::ANY_EXTEND:
6922   case ISD::ANY_EXTEND_VECTOR_INREG:
6923     return ISD::ANY_EXTEND;
6924   case ISD::ZERO_EXTEND:
6925   case ISD::ZERO_EXTEND_VECTOR_INREG:
6926     return ISD::ZERO_EXTEND;
6927   case ISD::SIGN_EXTEND:
6928   case ISD::SIGN_EXTEND_VECTOR_INREG:
6929     return ISD::SIGN_EXTEND;
6930   }
6931   llvm_unreachable("Unknown opcode");
6932 }
6933 
6934 // Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
6935 static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
6936   switch (Opcode) {
6937   case ISD::ANY_EXTEND:
6938   case ISD::ANY_EXTEND_VECTOR_INREG:
6939     return ISD::ANY_EXTEND_VECTOR_INREG;
6940   case ISD::ZERO_EXTEND:
6941   case ISD::ZERO_EXTEND_VECTOR_INREG:
6942     return ISD::ZERO_EXTEND_VECTOR_INREG;
6943   case ISD::SIGN_EXTEND:
6944   case ISD::SIGN_EXTEND_VECTOR_INREG:
6945     return ISD::SIGN_EXTEND_VECTOR_INREG;
6946   }
6947   llvm_unreachable("Unknown opcode");
6948 }
6949 
6950 static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
6951                                       SDValue In, SelectionDAG &DAG) {
6952   EVT InVT = In.getValueType();
6953   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
6954   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
6955           ISD::ZERO_EXTEND == Opcode) &&
6956          "Unknown extension opcode");
6957 
6958   // For 256-bit vectors, we only need the lower (128-bit) input half.
6959   // For 512-bit vectors, we only need the lower input half or quarter.
6960   if (InVT.getSizeInBits() > 128) {
6961     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
6962            "Expected VTs to be the same size!");
6963     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
6964     In = extractSubVector(In, 0, DAG, DL,
6965                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
6966     InVT = In.getValueType();
6967   }
6968 
6969   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
6970     Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
6971 
6972   return DAG.getNode(Opcode, DL, VT, In);
6973 }
6974 
6975 // Match (xor X, -1) -> X.
6976 // Match extract_subvector(xor X, -1) -> extract_subvector(X).
6977 // Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
6978 static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
6979   V = peekThroughBitcasts(V);
6980   if (V.getOpcode() == ISD::XOR &&
6981       ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
6982     return V.getOperand(0);
6983   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6984       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
6985     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
6986       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
6987       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
6988                          Not, V.getOperand(1));
6989     }
6990   }
6991   SmallVector<SDValue, 2> CatOps;
6992   if (collectConcatOps(V.getNode(), CatOps, DAG)) {
6993     for (SDValue &CatOp : CatOps) {
6994       SDValue NotCat = IsNOT(CatOp, DAG);
6995       if (!NotCat) return SDValue();
6996       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
6997     }
6998     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
6999   }
7000   return SDValue();
7001 }
7002 
7003 void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
7004                                    bool Lo, bool Unary) {
7005   assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
7006          "Illegal vector type to unpack");
7007   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7008   int NumElts = VT.getVectorNumElements();
7009   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
7010   for (int i = 0; i < NumElts; ++i) {
7011     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
7012     int Pos = (i % NumEltsInLane) / 2 + LaneStart;
7013     Pos += (Unary ? 0 : NumElts * (i % 2));
7014     Pos += (Lo ? 0 : NumEltsInLane / 2);
7015     Mask.push_back(Pos);
7016   }
7017 }
7018 
7019 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
7020 /// imposed by AVX and specific to the unary pattern. Example:
7021 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
7022 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
7023 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
7024                                    bool Lo) {
7025   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7026   int NumElts = VT.getVectorNumElements();
7027   for (int i = 0; i < NumElts; ++i) {
7028     int Pos = i / 2;
7029     Pos += (Lo ? 0 : NumElts / 2);
7030     Mask.push_back(Pos);
7031   }
7032 }
7033 
7034 // Attempt to constant fold, else just create a VECTOR_SHUFFLE.
7035 static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
7036                                 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
7037   if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
7038       (ISD::isBuildVectorOfConstantSDNodes(V2.getNode()) || V2.isUndef())) {
7039     SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
7040     for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
7041       int M = Mask[I];
7042       if (M < 0)
7043         continue;
7044       SDValue V = (M < NumElts) ? V1 : V2;
7045       if (V.isUndef())
7046         continue;
7047       Ops[I] = V.getOperand(M % NumElts);
7048     }
7049     return DAG.getBuildVector(VT, dl, Ops);
7050   }
7051 
7052   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
7053 }
7054 
7055 /// Returns a vector_shuffle node for an unpackl operation.
7056 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
7057                           SDValue V1, SDValue V2) {
7058   SmallVector<int, 8> Mask;
7059   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
7060   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
7061 }
7062 
7063 /// Returns a vector_shuffle node for an unpackh operation.
7064 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
7065                           SDValue V1, SDValue V2) {
7066   SmallVector<int, 8> Mask;
7067   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
7068   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
7069 }
7070 
7071 /// Returns a node that packs the LHS + RHS nodes together at half width.
7072 /// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
7073 /// TODO: Add subvector splitting if/when we have a need for it.
7074 static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
7075                        const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
7076                        bool PackHiHalf = false) {
7077   MVT OpVT = LHS.getSimpleValueType();
7078   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7079   bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
7080   assert(OpVT == RHS.getSimpleValueType() &&
7081          VT.getSizeInBits() == OpVT.getSizeInBits() &&
7082          (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
7083          "Unexpected PACK operand types");
7084   assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
7085          "Unexpected PACK result type");
7086 
7087   // Rely on vector shuffles for vXi64 -> vXi32 packing.
7088   if (EltSizeInBits == 32) {
7089     SmallVector<int> PackMask;
7090     int Offset = PackHiHalf ? 1 : 0;
7091     int NumElts = VT.getVectorNumElements();
7092     for (int I = 0; I != NumElts; I += 4) {
7093       PackMask.push_back(I + Offset);
7094       PackMask.push_back(I + Offset + 2);
7095       PackMask.push_back(I + Offset + NumElts);
7096       PackMask.push_back(I + Offset + NumElts + 2);
7097     }
7098     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
7099                                 DAG.getBitcast(VT, RHS), PackMask);
7100   }
7101 
7102   // See if we already have sufficient leading bits for PACKSS/PACKUS.
7103   if (!PackHiHalf) {
7104     if (UsePackUS &&
7105         DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
7106         DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
7107       return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
7108 
7109     if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
7110         DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
7111       return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
7112   }
7113 
7114   // Fallback to sign/zero extending the requested half and pack.
7115   SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
7116   if (UsePackUS) {
7117     if (PackHiHalf) {
7118       LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
7119       RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
7120     } else {
7121       SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
7122       LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
7123       RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
7124     };
7125     return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
7126   };
7127 
7128   if (!PackHiHalf) {
7129     LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
7130     RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
7131   }
7132   LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
7133   RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
7134   return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
7135 }
7136 
7137 /// Return a vector_shuffle of the specified vector of zero or undef vector.
7138 /// This produces a shuffle where the low element of V2 is swizzled into the
7139 /// zero/undef vector, landing at element Idx.
7140 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
7141 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
7142                                            bool IsZero,
7143                                            const X86Subtarget &Subtarget,
7144                                            SelectionDAG &DAG) {
7145   MVT VT = V2.getSimpleValueType();
7146   SDValue V1 = IsZero
7147     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
7148   int NumElems = VT.getVectorNumElements();
7149   SmallVector<int, 16> MaskVec(NumElems);
7150   for (int i = 0; i != NumElems; ++i)
7151     // If this is the insertion idx, put the low elt of V2 here.
7152     MaskVec[i] = (i == Idx) ? NumElems : i;
7153   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
7154 }
7155 
7156 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
7157   if (Ptr.getOpcode() == X86ISD::Wrapper ||
7158       Ptr.getOpcode() == X86ISD::WrapperRIP)
7159     Ptr = Ptr.getOperand(0);
7160 
7161   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
7162   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
7163     return nullptr;
7164 
7165   return CNode->getConstVal();
7166 }
7167 
7168 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
7169   if (!Load || !ISD::isNormalLoad(Load))
7170     return nullptr;
7171   return getTargetConstantFromBasePtr(Load->getBasePtr());
7172 }
7173 
7174 static const Constant *getTargetConstantFromNode(SDValue Op) {
7175   Op = peekThroughBitcasts(Op);
7176   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
7177 }
7178 
7179 const Constant *
7180 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
7181   assert(LD && "Unexpected null LoadSDNode");
7182   return getTargetConstantFromNode(LD);
7183 }
7184 
7185 // Extract raw constant bits from constant pools.
7186 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
7187                                           APInt &UndefElts,
7188                                           SmallVectorImpl<APInt> &EltBits,
7189                                           bool AllowWholeUndefs = true,
7190                                           bool AllowPartialUndefs = true) {
7191   assert(EltBits.empty() && "Expected an empty EltBits vector");
7192 
7193   Op = peekThroughBitcasts(Op);
7194 
7195   EVT VT = Op.getValueType();
7196   unsigned SizeInBits = VT.getSizeInBits();
7197   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
7198   unsigned NumElts = SizeInBits / EltSizeInBits;
7199 
7200   // Bitcast a source array of element bits to the target size.
7201   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
7202     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
7203     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
7204     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
7205            "Constant bit sizes don't match");
7206 
7207     // Don't split if we don't allow undef bits.
7208     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
7209     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
7210       return false;
7211 
7212     // If we're already the right size, don't bother bitcasting.
7213     if (NumSrcElts == NumElts) {
7214       UndefElts = UndefSrcElts;
7215       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
7216       return true;
7217     }
7218 
7219     // Extract all the undef/constant element data and pack into single bitsets.
7220     APInt UndefBits(SizeInBits, 0);
7221     APInt MaskBits(SizeInBits, 0);
7222 
7223     for (unsigned i = 0; i != NumSrcElts; ++i) {
7224       unsigned BitOffset = i * SrcEltSizeInBits;
7225       if (UndefSrcElts[i])
7226         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
7227       MaskBits.insertBits(SrcEltBits[i], BitOffset);
7228     }
7229 
7230     // Split the undef/constant single bitset data into the target elements.
7231     UndefElts = APInt(NumElts, 0);
7232     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
7233 
7234     for (unsigned i = 0; i != NumElts; ++i) {
7235       unsigned BitOffset = i * EltSizeInBits;
7236       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
7237 
7238       // Only treat an element as UNDEF if all bits are UNDEF.
7239       if (UndefEltBits.isAllOnes()) {
7240         if (!AllowWholeUndefs)
7241           return false;
7242         UndefElts.setBit(i);
7243         continue;
7244       }
7245 
7246       // If only some bits are UNDEF then treat them as zero (or bail if not
7247       // supported).
7248       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
7249         return false;
7250 
7251       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
7252     }
7253     return true;
7254   };
7255 
7256   // Collect constant bits and insert into mask/undef bit masks.
7257   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
7258                                 unsigned UndefBitIndex) {
7259     if (!Cst)
7260       return false;
7261     if (isa<UndefValue>(Cst)) {
7262       Undefs.setBit(UndefBitIndex);
7263       return true;
7264     }
7265     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
7266       Mask = CInt->getValue();
7267       return true;
7268     }
7269     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
7270       Mask = CFP->getValueAPF().bitcastToAPInt();
7271       return true;
7272     }
7273     return false;
7274   };
7275 
7276   // Handle UNDEFs.
7277   if (Op.isUndef()) {
7278     APInt UndefSrcElts = APInt::getAllOnes(NumElts);
7279     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
7280     return CastBitData(UndefSrcElts, SrcEltBits);
7281   }
7282 
7283   // Extract scalar constant bits.
7284   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
7285     APInt UndefSrcElts = APInt::getZero(1);
7286     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
7287     return CastBitData(UndefSrcElts, SrcEltBits);
7288   }
7289   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7290     APInt UndefSrcElts = APInt::getZero(1);
7291     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
7292     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
7293     return CastBitData(UndefSrcElts, SrcEltBits);
7294   }
7295 
7296   // Extract constant bits from build vector.
7297   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
7298     BitVector Undefs;
7299     SmallVector<APInt> SrcEltBits;
7300     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7301     if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
7302       APInt UndefSrcElts = APInt::getNullValue(SrcEltBits.size());
7303       for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
7304         if (Undefs[I])
7305           UndefSrcElts.setBit(I);
7306       return CastBitData(UndefSrcElts, SrcEltBits);
7307     }
7308   }
7309 
7310   // Extract constant bits from constant pool vector.
7311   if (auto *Cst = getTargetConstantFromNode(Op)) {
7312     Type *CstTy = Cst->getType();
7313     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
7314     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
7315       return false;
7316 
7317     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
7318     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7319 
7320     APInt UndefSrcElts(NumSrcElts, 0);
7321     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
7322     for (unsigned i = 0; i != NumSrcElts; ++i)
7323       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
7324                                UndefSrcElts, i))
7325         return false;
7326 
7327     return CastBitData(UndefSrcElts, SrcEltBits);
7328   }
7329 
7330   // Extract constant bits from a broadcasted constant pool scalar.
7331   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
7332       EltSizeInBits <= VT.getScalarSizeInBits()) {
7333     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
7334     if (MemIntr->getMemoryVT().getScalarSizeInBits() != VT.getScalarSizeInBits())
7335       return false;
7336 
7337     SDValue Ptr = MemIntr->getBasePtr();
7338     if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
7339       unsigned SrcEltSizeInBits = C->getType()->getScalarSizeInBits();
7340       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7341 
7342       APInt UndefSrcElts(NumSrcElts, 0);
7343       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
7344       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
7345         if (UndefSrcElts[0])
7346           UndefSrcElts.setBits(0, NumSrcElts);
7347         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
7348         return CastBitData(UndefSrcElts, SrcEltBits);
7349       }
7350     }
7351   }
7352 
7353   // Extract constant bits from a subvector broadcast.
7354   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
7355     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
7356     SDValue Ptr = MemIntr->getBasePtr();
7357     // The source constant may be larger than the subvector broadcast,
7358     // ensure we extract the correct subvector constants.
7359     if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
7360       Type *CstTy = Cst->getType();
7361       unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
7362       unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
7363       if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
7364           (SizeInBits % SubVecSizeInBits) != 0)
7365         return false;
7366       unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
7367       unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
7368       unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
7369       APInt UndefSubElts(NumSubElts, 0);
7370       SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
7371                                         APInt(CstEltSizeInBits, 0));
7372       for (unsigned i = 0; i != NumSubElts; ++i) {
7373         if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
7374                                  UndefSubElts, i))
7375           return false;
7376         for (unsigned j = 1; j != NumSubVecs; ++j)
7377           SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
7378       }
7379       UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
7380                                      UndefSubElts);
7381       return CastBitData(UndefSubElts, SubEltBits);
7382     }
7383   }
7384 
7385   // Extract a rematerialized scalar constant insertion.
7386   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
7387       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7388       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
7389     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7390     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7391 
7392     APInt UndefSrcElts(NumSrcElts, 0);
7393     SmallVector<APInt, 64> SrcEltBits;
7394     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
7395     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
7396     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
7397     return CastBitData(UndefSrcElts, SrcEltBits);
7398   }
7399 
7400   // Insert constant bits from a base and sub vector sources.
7401   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
7402     // If bitcasts to larger elements we might lose track of undefs - don't
7403     // allow any to be safe.
7404     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7405     bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
7406 
7407     APInt UndefSrcElts, UndefSubElts;
7408     SmallVector<APInt, 32> EltSrcBits, EltSubBits;
7409     if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
7410                                       UndefSubElts, EltSubBits,
7411                                       AllowWholeUndefs && AllowUndefs,
7412                                       AllowPartialUndefs && AllowUndefs) &&
7413         getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
7414                                       UndefSrcElts, EltSrcBits,
7415                                       AllowWholeUndefs && AllowUndefs,
7416                                       AllowPartialUndefs && AllowUndefs)) {
7417       unsigned BaseIdx = Op.getConstantOperandVal(2);
7418       UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
7419       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
7420         EltSrcBits[BaseIdx + i] = EltSubBits[i];
7421       return CastBitData(UndefSrcElts, EltSrcBits);
7422     }
7423   }
7424 
7425   // Extract constant bits from a subvector's source.
7426   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7427     // TODO - support extract_subvector through bitcasts.
7428     if (EltSizeInBits != VT.getScalarSizeInBits())
7429       return false;
7430 
7431     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
7432                                       UndefElts, EltBits, AllowWholeUndefs,
7433                                       AllowPartialUndefs)) {
7434       EVT SrcVT = Op.getOperand(0).getValueType();
7435       unsigned NumSrcElts = SrcVT.getVectorNumElements();
7436       unsigned NumSubElts = VT.getVectorNumElements();
7437       unsigned BaseIdx = Op.getConstantOperandVal(1);
7438       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
7439       if ((BaseIdx + NumSubElts) != NumSrcElts)
7440         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
7441       if (BaseIdx != 0)
7442         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
7443       return true;
7444     }
7445   }
7446 
7447   // Extract constant bits from shuffle node sources.
7448   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
7449     // TODO - support shuffle through bitcasts.
7450     if (EltSizeInBits != VT.getScalarSizeInBits())
7451       return false;
7452 
7453     ArrayRef<int> Mask = SVN->getMask();
7454     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
7455         llvm::any_of(Mask, [](int M) { return M < 0; }))
7456       return false;
7457 
7458     APInt UndefElts0, UndefElts1;
7459     SmallVector<APInt, 32> EltBits0, EltBits1;
7460     if (isAnyInRange(Mask, 0, NumElts) &&
7461         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
7462                                        UndefElts0, EltBits0, AllowWholeUndefs,
7463                                        AllowPartialUndefs))
7464       return false;
7465     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
7466         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
7467                                        UndefElts1, EltBits1, AllowWholeUndefs,
7468                                        AllowPartialUndefs))
7469       return false;
7470 
7471     UndefElts = APInt::getZero(NumElts);
7472     for (int i = 0; i != (int)NumElts; ++i) {
7473       int M = Mask[i];
7474       if (M < 0) {
7475         UndefElts.setBit(i);
7476         EltBits.push_back(APInt::getZero(EltSizeInBits));
7477       } else if (M < (int)NumElts) {
7478         if (UndefElts0[M])
7479           UndefElts.setBit(i);
7480         EltBits.push_back(EltBits0[M]);
7481       } else {
7482         if (UndefElts1[M - NumElts])
7483           UndefElts.setBit(i);
7484         EltBits.push_back(EltBits1[M - NumElts]);
7485       }
7486     }
7487     return true;
7488   }
7489 
7490   return false;
7491 }
7492 
7493 namespace llvm {
7494 namespace X86 {
7495 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
7496   APInt UndefElts;
7497   SmallVector<APInt, 16> EltBits;
7498   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
7499                                     UndefElts, EltBits, true,
7500                                     AllowPartialUndefs)) {
7501     int SplatIndex = -1;
7502     for (int i = 0, e = EltBits.size(); i != e; ++i) {
7503       if (UndefElts[i])
7504         continue;
7505       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
7506         SplatIndex = -1;
7507         break;
7508       }
7509       SplatIndex = i;
7510     }
7511     if (0 <= SplatIndex) {
7512       SplatVal = EltBits[SplatIndex];
7513       return true;
7514     }
7515   }
7516 
7517   return false;
7518 }
7519 } // namespace X86
7520 } // namespace llvm
7521 
7522 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
7523                                         unsigned MaskEltSizeInBits,
7524                                         SmallVectorImpl<uint64_t> &RawMask,
7525                                         APInt &UndefElts) {
7526   // Extract the raw target constant bits.
7527   SmallVector<APInt, 64> EltBits;
7528   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
7529                                      EltBits, /* AllowWholeUndefs */ true,
7530                                      /* AllowPartialUndefs */ false))
7531     return false;
7532 
7533   // Insert the extracted elements into the mask.
7534   for (const APInt &Elt : EltBits)
7535     RawMask.push_back(Elt.getZExtValue());
7536 
7537   return true;
7538 }
7539 
7540 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
7541 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
7542 /// Note: This ignores saturation, so inputs must be checked first.
7543 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
7544                                   bool Unary, unsigned NumStages = 1) {
7545   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7546   unsigned NumElts = VT.getVectorNumElements();
7547   unsigned NumLanes = VT.getSizeInBits() / 128;
7548   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
7549   unsigned Offset = Unary ? 0 : NumElts;
7550   unsigned Repetitions = 1u << (NumStages - 1);
7551   unsigned Increment = 1u << NumStages;
7552   assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
7553 
7554   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
7555     for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
7556       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
7557         Mask.push_back(Elt + (Lane * NumEltsPerLane));
7558       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
7559         Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
7560     }
7561   }
7562 }
7563 
7564 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
7565 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
7566                                 APInt &DemandedLHS, APInt &DemandedRHS) {
7567   int NumLanes = VT.getSizeInBits() / 128;
7568   int NumElts = DemandedElts.getBitWidth();
7569   int NumInnerElts = NumElts / 2;
7570   int NumEltsPerLane = NumElts / NumLanes;
7571   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
7572 
7573   DemandedLHS = APInt::getZero(NumInnerElts);
7574   DemandedRHS = APInt::getZero(NumInnerElts);
7575 
7576   // Map DemandedElts to the packed operands.
7577   for (int Lane = 0; Lane != NumLanes; ++Lane) {
7578     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
7579       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
7580       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
7581       if (DemandedElts[OuterIdx])
7582         DemandedLHS.setBit(InnerIdx);
7583       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
7584         DemandedRHS.setBit(InnerIdx);
7585     }
7586   }
7587 }
7588 
7589 // Split the demanded elts of a HADD/HSUB node between its operands.
7590 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
7591                                  APInt &DemandedLHS, APInt &DemandedRHS) {
7592   int NumLanes = VT.getSizeInBits() / 128;
7593   int NumElts = DemandedElts.getBitWidth();
7594   int NumEltsPerLane = NumElts / NumLanes;
7595   int HalfEltsPerLane = NumEltsPerLane / 2;
7596 
7597   DemandedLHS = APInt::getZero(NumElts);
7598   DemandedRHS = APInt::getZero(NumElts);
7599 
7600   // Map DemandedElts to the horizontal operands.
7601   for (int Idx = 0; Idx != NumElts; ++Idx) {
7602     if (!DemandedElts[Idx])
7603       continue;
7604     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
7605     int LocalIdx = Idx % NumEltsPerLane;
7606     if (LocalIdx < HalfEltsPerLane) {
7607       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
7608       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
7609     } else {
7610       LocalIdx -= HalfEltsPerLane;
7611       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
7612       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
7613     }
7614   }
7615 }
7616 
7617 /// Calculates the shuffle mask corresponding to the target-specific opcode.
7618 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
7619 /// operands in \p Ops, and returns true.
7620 /// Sets \p IsUnary to true if only one source is used. Note that this will set
7621 /// IsUnary for shuffles which use a single input multiple times, and in those
7622 /// cases it will adjust the mask to only have indices within that single input.
7623 /// It is an error to call this with non-empty Mask/Ops vectors.
7624 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
7625                                  SmallVectorImpl<SDValue> &Ops,
7626                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
7627   unsigned NumElems = VT.getVectorNumElements();
7628   unsigned MaskEltSize = VT.getScalarSizeInBits();
7629   SmallVector<uint64_t, 32> RawMask;
7630   APInt RawUndefs;
7631   uint64_t ImmN;
7632 
7633   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
7634   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
7635 
7636   IsUnary = false;
7637   bool IsFakeUnary = false;
7638   switch (N->getOpcode()) {
7639   case X86ISD::BLENDI:
7640     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7641     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7642     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7643     DecodeBLENDMask(NumElems, ImmN, Mask);
7644     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7645     break;
7646   case X86ISD::SHUFP:
7647     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7648     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7649     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7650     DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
7651     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7652     break;
7653   case X86ISD::INSERTPS:
7654     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7655     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7656     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7657     DecodeINSERTPSMask(ImmN, Mask);
7658     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7659     break;
7660   case X86ISD::EXTRQI:
7661     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7662     if (isa<ConstantSDNode>(N->getOperand(1)) &&
7663         isa<ConstantSDNode>(N->getOperand(2))) {
7664       int BitLen = N->getConstantOperandVal(1);
7665       int BitIdx = N->getConstantOperandVal(2);
7666       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7667       IsUnary = true;
7668     }
7669     break;
7670   case X86ISD::INSERTQI:
7671     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7672     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7673     if (isa<ConstantSDNode>(N->getOperand(2)) &&
7674         isa<ConstantSDNode>(N->getOperand(3))) {
7675       int BitLen = N->getConstantOperandVal(2);
7676       int BitIdx = N->getConstantOperandVal(3);
7677       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7678       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7679     }
7680     break;
7681   case X86ISD::UNPCKH:
7682     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7683     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7684     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
7685     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7686     break;
7687   case X86ISD::UNPCKL:
7688     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7689     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7690     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
7691     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7692     break;
7693   case X86ISD::MOVHLPS:
7694     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7695     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7696     DecodeMOVHLPSMask(NumElems, Mask);
7697     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7698     break;
7699   case X86ISD::MOVLHPS:
7700     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7701     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7702     DecodeMOVLHPSMask(NumElems, Mask);
7703     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7704     break;
7705   case X86ISD::VALIGN:
7706     assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
7707            "Only 32-bit and 64-bit elements are supported!");
7708     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7709     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7710     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7711     DecodeVALIGNMask(NumElems, ImmN, Mask);
7712     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7713     Ops.push_back(N->getOperand(1));
7714     Ops.push_back(N->getOperand(0));
7715     break;
7716   case X86ISD::PALIGNR:
7717     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7718     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7719     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7720     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7721     DecodePALIGNRMask(NumElems, ImmN, Mask);
7722     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7723     Ops.push_back(N->getOperand(1));
7724     Ops.push_back(N->getOperand(0));
7725     break;
7726   case X86ISD::VSHLDQ:
7727     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7728     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7729     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7730     DecodePSLLDQMask(NumElems, ImmN, Mask);
7731     IsUnary = true;
7732     break;
7733   case X86ISD::VSRLDQ:
7734     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7735     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7736     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7737     DecodePSRLDQMask(NumElems, ImmN, Mask);
7738     IsUnary = true;
7739     break;
7740   case X86ISD::PSHUFD:
7741   case X86ISD::VPERMILPI:
7742     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7743     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7744     DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
7745     IsUnary = true;
7746     break;
7747   case X86ISD::PSHUFHW:
7748     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7749     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7750     DecodePSHUFHWMask(NumElems, ImmN, Mask);
7751     IsUnary = true;
7752     break;
7753   case X86ISD::PSHUFLW:
7754     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7755     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7756     DecodePSHUFLWMask(NumElems, ImmN, Mask);
7757     IsUnary = true;
7758     break;
7759   case X86ISD::VZEXT_MOVL:
7760     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7761     DecodeZeroMoveLowMask(NumElems, Mask);
7762     IsUnary = true;
7763     break;
7764   case X86ISD::VBROADCAST:
7765     // We only decode broadcasts of same-sized vectors, peeking through to
7766     // extracted subvectors is likely to cause hasOneUse issues with
7767     // SimplifyDemandedBits etc.
7768     if (N->getOperand(0).getValueType() == VT) {
7769       DecodeVectorBroadcast(NumElems, Mask);
7770       IsUnary = true;
7771       break;
7772     }
7773     return false;
7774   case X86ISD::VPERMILPV: {
7775     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7776     IsUnary = true;
7777     SDValue MaskNode = N->getOperand(1);
7778     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7779                                     RawUndefs)) {
7780       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
7781       break;
7782     }
7783     return false;
7784   }
7785   case X86ISD::PSHUFB: {
7786     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7787     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7788     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7789     IsUnary = true;
7790     SDValue MaskNode = N->getOperand(1);
7791     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7792       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
7793       break;
7794     }
7795     return false;
7796   }
7797   case X86ISD::VPERMI:
7798     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7799     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7800     DecodeVPERMMask(NumElems, ImmN, Mask);
7801     IsUnary = true;
7802     break;
7803   case X86ISD::MOVSS:
7804   case X86ISD::MOVSD:
7805   case X86ISD::MOVSH:
7806     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7807     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7808     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
7809     break;
7810   case X86ISD::VPERM2X128:
7811     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7812     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7813     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7814     DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
7815     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7816     break;
7817   case X86ISD::SHUF128:
7818     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7819     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7820     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7821     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
7822     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7823     break;
7824   case X86ISD::MOVSLDUP:
7825     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7826     DecodeMOVSLDUPMask(NumElems, Mask);
7827     IsUnary = true;
7828     break;
7829   case X86ISD::MOVSHDUP:
7830     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7831     DecodeMOVSHDUPMask(NumElems, Mask);
7832     IsUnary = true;
7833     break;
7834   case X86ISD::MOVDDUP:
7835     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7836     DecodeMOVDDUPMask(NumElems, Mask);
7837     IsUnary = true;
7838     break;
7839   case X86ISD::VPERMIL2: {
7840     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7841     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7842     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7843     SDValue MaskNode = N->getOperand(2);
7844     SDValue CtrlNode = N->getOperand(3);
7845     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
7846       unsigned CtrlImm = CtrlOp->getZExtValue();
7847       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7848                                       RawUndefs)) {
7849         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
7850                             Mask);
7851         break;
7852       }
7853     }
7854     return false;
7855   }
7856   case X86ISD::VPPERM: {
7857     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7858     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7859     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7860     SDValue MaskNode = N->getOperand(2);
7861     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7862       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
7863       break;
7864     }
7865     return false;
7866   }
7867   case X86ISD::VPERMV: {
7868     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7869     IsUnary = true;
7870     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
7871     Ops.push_back(N->getOperand(1));
7872     SDValue MaskNode = N->getOperand(0);
7873     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7874                                     RawUndefs)) {
7875       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
7876       break;
7877     }
7878     return false;
7879   }
7880   case X86ISD::VPERMV3: {
7881     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7882     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
7883     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
7884     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
7885     Ops.push_back(N->getOperand(0));
7886     Ops.push_back(N->getOperand(2));
7887     SDValue MaskNode = N->getOperand(1);
7888     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7889                                     RawUndefs)) {
7890       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
7891       break;
7892     }
7893     return false;
7894   }
7895   default: llvm_unreachable("unknown target shuffle node");
7896   }
7897 
7898   // Empty mask indicates the decode failed.
7899   if (Mask.empty())
7900     return false;
7901 
7902   // Check if we're getting a shuffle mask with zero'd elements.
7903   if (!AllowSentinelZero && isAnyZero(Mask))
7904     return false;
7905 
7906   // If we have a fake unary shuffle, the shuffle mask is spread across two
7907   // inputs that are actually the same node. Re-map the mask to always point
7908   // into the first input.
7909   if (IsFakeUnary)
7910     for (int &M : Mask)
7911       if (M >= (int)Mask.size())
7912         M -= Mask.size();
7913 
7914   // If we didn't already add operands in the opcode-specific code, default to
7915   // adding 1 or 2 operands starting at 0.
7916   if (Ops.empty()) {
7917     Ops.push_back(N->getOperand(0));
7918     if (!IsUnary || IsFakeUnary)
7919       Ops.push_back(N->getOperand(1));
7920   }
7921 
7922   return true;
7923 }
7924 
7925 // Wrapper for getTargetShuffleMask with InUnary;
7926 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
7927                                  SmallVectorImpl<SDValue> &Ops,
7928                                  SmallVectorImpl<int> &Mask) {
7929   bool IsUnary;
7930   return getTargetShuffleMask(N, VT, AllowSentinelZero, Ops, Mask, IsUnary);
7931 }
7932 
7933 /// Compute whether each element of a shuffle is zeroable.
7934 ///
7935 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7936 /// Either it is an undef element in the shuffle mask, the element of the input
7937 /// referenced is undef, or the element of the input referenced is known to be
7938 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7939 /// as many lanes with this technique as possible to simplify the remaining
7940 /// shuffle.
7941 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
7942                                            SDValue V1, SDValue V2,
7943                                            APInt &KnownUndef, APInt &KnownZero) {
7944   int Size = Mask.size();
7945   KnownUndef = KnownZero = APInt::getZero(Size);
7946 
7947   V1 = peekThroughBitcasts(V1);
7948   V2 = peekThroughBitcasts(V2);
7949 
7950   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7951   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7952 
7953   int VectorSizeInBits = V1.getValueSizeInBits();
7954   int ScalarSizeInBits = VectorSizeInBits / Size;
7955   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
7956 
7957   for (int i = 0; i < Size; ++i) {
7958     int M = Mask[i];
7959     // Handle the easy cases.
7960     if (M < 0) {
7961       KnownUndef.setBit(i);
7962       continue;
7963     }
7964     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7965       KnownZero.setBit(i);
7966       continue;
7967     }
7968 
7969     // Determine shuffle input and normalize the mask.
7970     SDValue V = M < Size ? V1 : V2;
7971     M %= Size;
7972 
7973     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
7974     if (V.getOpcode() != ISD::BUILD_VECTOR)
7975       continue;
7976 
7977     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
7978     // the (larger) source element must be UNDEF/ZERO.
7979     if ((Size % V.getNumOperands()) == 0) {
7980       int Scale = Size / V->getNumOperands();
7981       SDValue Op = V.getOperand(M / Scale);
7982       if (Op.isUndef())
7983         KnownUndef.setBit(i);
7984       if (X86::isZeroNode(Op))
7985         KnownZero.setBit(i);
7986       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
7987         APInt Val = Cst->getAPIntValue();
7988         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7989         if (Val == 0)
7990           KnownZero.setBit(i);
7991       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7992         APInt Val = Cst->getValueAPF().bitcastToAPInt();
7993         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7994         if (Val == 0)
7995           KnownZero.setBit(i);
7996       }
7997       continue;
7998     }
7999 
8000     // If the BUILD_VECTOR has more elements then all the (smaller) source
8001     // elements must be UNDEF or ZERO.
8002     if ((V.getNumOperands() % Size) == 0) {
8003       int Scale = V->getNumOperands() / Size;
8004       bool AllUndef = true;
8005       bool AllZero = true;
8006       for (int j = 0; j < Scale; ++j) {
8007         SDValue Op = V.getOperand((M * Scale) + j);
8008         AllUndef &= Op.isUndef();
8009         AllZero &= X86::isZeroNode(Op);
8010       }
8011       if (AllUndef)
8012         KnownUndef.setBit(i);
8013       if (AllZero)
8014         KnownZero.setBit(i);
8015       continue;
8016     }
8017   }
8018 }
8019 
8020 /// Decode a target shuffle mask and inputs and see if any values are
8021 /// known to be undef or zero from their inputs.
8022 /// Returns true if the target shuffle mask was decoded.
8023 /// FIXME: Merge this with computeZeroableShuffleElements?
8024 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
8025                                          SmallVectorImpl<SDValue> &Ops,
8026                                          APInt &KnownUndef, APInt &KnownZero) {
8027   bool IsUnary;
8028   if (!isTargetShuffle(N.getOpcode()))
8029     return false;
8030 
8031   MVT VT = N.getSimpleValueType();
8032   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
8033     return false;
8034 
8035   int Size = Mask.size();
8036   SDValue V1 = Ops[0];
8037   SDValue V2 = IsUnary ? V1 : Ops[1];
8038   KnownUndef = KnownZero = APInt::getZero(Size);
8039 
8040   V1 = peekThroughBitcasts(V1);
8041   V2 = peekThroughBitcasts(V2);
8042 
8043   assert((VT.getSizeInBits() % Size) == 0 &&
8044          "Illegal split of shuffle value type");
8045   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
8046 
8047   // Extract known constant input data.
8048   APInt UndefSrcElts[2];
8049   SmallVector<APInt, 32> SrcEltBits[2];
8050   bool IsSrcConstant[2] = {
8051       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
8052                                     SrcEltBits[0], true, false),
8053       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
8054                                     SrcEltBits[1], true, false)};
8055 
8056   for (int i = 0; i < Size; ++i) {
8057     int M = Mask[i];
8058 
8059     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
8060     if (M < 0) {
8061       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
8062       if (SM_SentinelUndef == M)
8063         KnownUndef.setBit(i);
8064       if (SM_SentinelZero == M)
8065         KnownZero.setBit(i);
8066       continue;
8067     }
8068 
8069     // Determine shuffle input and normalize the mask.
8070     unsigned SrcIdx = M / Size;
8071     SDValue V = M < Size ? V1 : V2;
8072     M %= Size;
8073 
8074     // We are referencing an UNDEF input.
8075     if (V.isUndef()) {
8076       KnownUndef.setBit(i);
8077       continue;
8078     }
8079 
8080     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
8081     // TODO: We currently only set UNDEF for integer types - floats use the same
8082     // registers as vectors and many of the scalar folded loads rely on the
8083     // SCALAR_TO_VECTOR pattern.
8084     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8085         (Size % V.getValueType().getVectorNumElements()) == 0) {
8086       int Scale = Size / V.getValueType().getVectorNumElements();
8087       int Idx = M / Scale;
8088       if (Idx != 0 && !VT.isFloatingPoint())
8089         KnownUndef.setBit(i);
8090       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
8091         KnownZero.setBit(i);
8092       continue;
8093     }
8094 
8095     // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
8096     // base vectors.
8097     if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
8098       SDValue Vec = V.getOperand(0);
8099       int NumVecElts = Vec.getValueType().getVectorNumElements();
8100       if (Vec.isUndef() && Size == NumVecElts) {
8101         int Idx = V.getConstantOperandVal(2);
8102         int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
8103         if (M < Idx || (Idx + NumSubElts) <= M)
8104           KnownUndef.setBit(i);
8105       }
8106       continue;
8107     }
8108 
8109     // Attempt to extract from the source's constant bits.
8110     if (IsSrcConstant[SrcIdx]) {
8111       if (UndefSrcElts[SrcIdx][M])
8112         KnownUndef.setBit(i);
8113       else if (SrcEltBits[SrcIdx][M] == 0)
8114         KnownZero.setBit(i);
8115     }
8116   }
8117 
8118   assert(VT.getVectorNumElements() == (unsigned)Size &&
8119          "Different mask size from vector size!");
8120   return true;
8121 }
8122 
8123 // Replace target shuffle mask elements with known undef/zero sentinels.
8124 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
8125                                               const APInt &KnownUndef,
8126                                               const APInt &KnownZero,
8127                                               bool ResolveKnownZeros= true) {
8128   unsigned NumElts = Mask.size();
8129   assert(KnownUndef.getBitWidth() == NumElts &&
8130          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
8131 
8132   for (unsigned i = 0; i != NumElts; ++i) {
8133     if (KnownUndef[i])
8134       Mask[i] = SM_SentinelUndef;
8135     else if (ResolveKnownZeros && KnownZero[i])
8136       Mask[i] = SM_SentinelZero;
8137   }
8138 }
8139 
8140 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
8141 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
8142                                               APInt &KnownUndef,
8143                                               APInt &KnownZero) {
8144   unsigned NumElts = Mask.size();
8145   KnownUndef = KnownZero = APInt::getZero(NumElts);
8146 
8147   for (unsigned i = 0; i != NumElts; ++i) {
8148     int M = Mask[i];
8149     if (SM_SentinelUndef == M)
8150       KnownUndef.setBit(i);
8151     if (SM_SentinelZero == M)
8152       KnownZero.setBit(i);
8153   }
8154 }
8155 
8156 // Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
8157 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
8158                                          SDValue Cond, bool IsBLENDV = false) {
8159   EVT CondVT = Cond.getValueType();
8160   unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
8161   unsigned NumElts = CondVT.getVectorNumElements();
8162 
8163   APInt UndefElts;
8164   SmallVector<APInt, 32> EltBits;
8165   if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
8166                                      true, false))
8167     return false;
8168 
8169   Mask.resize(NumElts, SM_SentinelUndef);
8170 
8171   for (int i = 0; i != (int)NumElts; ++i) {
8172     Mask[i] = i;
8173     // Arbitrarily choose from the 2nd operand if the select condition element
8174     // is undef.
8175     // TODO: Can we do better by matching patterns such as even/odd?
8176     if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
8177         (IsBLENDV && EltBits[i].isNonNegative()))
8178       Mask[i] += NumElts;
8179   }
8180 
8181   return true;
8182 }
8183 
8184 // Forward declaration (for getFauxShuffleMask recursive check).
8185 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
8186                                    SmallVectorImpl<int> &Mask,
8187                                    const SelectionDAG &DAG, unsigned Depth,
8188                                    bool ResolveKnownElts);
8189 
8190 // Attempt to decode ops that could be represented as a shuffle mask.
8191 // The decoded shuffle mask may contain a different number of elements to the
8192 // destination value type.
8193 // TODO: Merge into getTargetShuffleInputs()
8194 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
8195                                SmallVectorImpl<int> &Mask,
8196                                SmallVectorImpl<SDValue> &Ops,
8197                                const SelectionDAG &DAG, unsigned Depth,
8198                                bool ResolveKnownElts) {
8199   Mask.clear();
8200   Ops.clear();
8201 
8202   MVT VT = N.getSimpleValueType();
8203   unsigned NumElts = VT.getVectorNumElements();
8204   unsigned NumSizeInBits = VT.getSizeInBits();
8205   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8206   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
8207     return false;
8208   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
8209   unsigned NumSizeInBytes = NumSizeInBits / 8;
8210   unsigned NumBytesPerElt = NumBitsPerElt / 8;
8211 
8212   unsigned Opcode = N.getOpcode();
8213   switch (Opcode) {
8214   case ISD::VECTOR_SHUFFLE: {
8215     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
8216     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
8217     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
8218       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
8219       Ops.push_back(N.getOperand(0));
8220       Ops.push_back(N.getOperand(1));
8221       return true;
8222     }
8223     return false;
8224   }
8225   case ISD::AND:
8226   case X86ISD::ANDNP: {
8227     // Attempt to decode as a per-byte mask.
8228     APInt UndefElts;
8229     SmallVector<APInt, 32> EltBits;
8230     SDValue N0 = N.getOperand(0);
8231     SDValue N1 = N.getOperand(1);
8232     bool IsAndN = (X86ISD::ANDNP == Opcode);
8233     uint64_t ZeroMask = IsAndN ? 255 : 0;
8234     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
8235       return false;
8236     // We can't assume an undef src element gives an undef dst - the other src
8237     // might be zero.
8238     if (!UndefElts.isZero())
8239       return false;
8240     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
8241       const APInt &ByteBits = EltBits[i];
8242       if (ByteBits != 0 && ByteBits != 255)
8243         return false;
8244       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
8245     }
8246     Ops.push_back(IsAndN ? N1 : N0);
8247     return true;
8248   }
8249   case ISD::OR: {
8250     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
8251     // is a valid shuffle index.
8252     SDValue N0 = peekThroughBitcasts(N.getOperand(0));
8253     SDValue N1 = peekThroughBitcasts(N.getOperand(1));
8254     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
8255       return false;
8256     SmallVector<int, 64> SrcMask0, SrcMask1;
8257     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
8258     if (!getTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG, Depth + 1,
8259                                 true) ||
8260         !getTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG, Depth + 1,
8261                                 true))
8262       return false;
8263 
8264     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
8265     SmallVector<int, 64> Mask0, Mask1;
8266     narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
8267     narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
8268     for (int i = 0; i != (int)MaskSize; ++i) {
8269       // NOTE: Don't handle SM_SentinelUndef, as we can end up in infinite
8270       // loops converting between OR and BLEND shuffles due to
8271       // canWidenShuffleElements merging away undef elements, meaning we
8272       // fail to recognise the OR as the undef element isn't known zero.
8273       if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
8274         Mask.push_back(SM_SentinelZero);
8275       else if (Mask1[i] == SM_SentinelZero)
8276         Mask.push_back(i);
8277       else if (Mask0[i] == SM_SentinelZero)
8278         Mask.push_back(i + MaskSize);
8279       else
8280         return false;
8281     }
8282     Ops.push_back(N0);
8283     Ops.push_back(N1);
8284     return true;
8285   }
8286   case ISD::INSERT_SUBVECTOR: {
8287     SDValue Src = N.getOperand(0);
8288     SDValue Sub = N.getOperand(1);
8289     EVT SubVT = Sub.getValueType();
8290     unsigned NumSubElts = SubVT.getVectorNumElements();
8291     if (!N->isOnlyUserOf(Sub.getNode()))
8292       return false;
8293     uint64_t InsertIdx = N.getConstantOperandVal(2);
8294     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
8295     if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8296         Sub.getOperand(0).getValueType() == VT) {
8297       uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
8298       for (int i = 0; i != (int)NumElts; ++i)
8299         Mask.push_back(i);
8300       for (int i = 0; i != (int)NumSubElts; ++i)
8301         Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
8302       Ops.push_back(Src);
8303       Ops.push_back(Sub.getOperand(0));
8304       return true;
8305     }
8306     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
8307     SmallVector<int, 64> SubMask;
8308     SmallVector<SDValue, 2> SubInputs;
8309     if (!getTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
8310                                 SubMask, DAG, Depth + 1, ResolveKnownElts))
8311       return false;
8312 
8313     // Subvector shuffle inputs must not be larger than the subvector.
8314     if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
8315           return SubVT.getFixedSizeInBits() <
8316                  SubInput.getValueSizeInBits().getFixedSize();
8317         }))
8318       return false;
8319 
8320     if (SubMask.size() != NumSubElts) {
8321       assert(((SubMask.size() % NumSubElts) == 0 ||
8322               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
8323       if ((NumSubElts % SubMask.size()) == 0) {
8324         int Scale = NumSubElts / SubMask.size();
8325         SmallVector<int,64> ScaledSubMask;
8326         narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
8327         SubMask = ScaledSubMask;
8328       } else {
8329         int Scale = SubMask.size() / NumSubElts;
8330         NumSubElts = SubMask.size();
8331         NumElts *= Scale;
8332         InsertIdx *= Scale;
8333       }
8334     }
8335     Ops.push_back(Src);
8336     Ops.append(SubInputs.begin(), SubInputs.end());
8337     if (ISD::isBuildVectorAllZeros(Src.getNode()))
8338       Mask.append(NumElts, SM_SentinelZero);
8339     else
8340       for (int i = 0; i != (int)NumElts; ++i)
8341         Mask.push_back(i);
8342     for (int i = 0; i != (int)NumSubElts; ++i) {
8343       int M = SubMask[i];
8344       if (0 <= M) {
8345         int InputIdx = M / NumSubElts;
8346         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
8347       }
8348       Mask[i + InsertIdx] = M;
8349     }
8350     return true;
8351   }
8352   case X86ISD::PINSRB:
8353   case X86ISD::PINSRW:
8354   case ISD::SCALAR_TO_VECTOR:
8355   case ISD::INSERT_VECTOR_ELT: {
8356     // Match against a insert_vector_elt/scalar_to_vector of an extract from a
8357     // vector, for matching src/dst vector types.
8358     SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
8359 
8360     unsigned DstIdx = 0;
8361     if (Opcode != ISD::SCALAR_TO_VECTOR) {
8362       // Check we have an in-range constant insertion index.
8363       if (!isa<ConstantSDNode>(N.getOperand(2)) ||
8364           N.getConstantOperandAPInt(2).uge(NumElts))
8365         return false;
8366       DstIdx = N.getConstantOperandVal(2);
8367 
8368       // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
8369       if (X86::isZeroNode(Scl)) {
8370         Ops.push_back(N.getOperand(0));
8371         for (unsigned i = 0; i != NumElts; ++i)
8372           Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
8373         return true;
8374       }
8375     }
8376 
8377     // Peek through trunc/aext/zext.
8378     // TODO: aext shouldn't require SM_SentinelZero padding.
8379     // TODO: handle shift of scalars.
8380     unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
8381     while (Scl.getOpcode() == ISD::TRUNCATE ||
8382            Scl.getOpcode() == ISD::ANY_EXTEND ||
8383            Scl.getOpcode() == ISD::ZERO_EXTEND) {
8384       Scl = Scl.getOperand(0);
8385       MinBitsPerElt =
8386           std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
8387     }
8388     if ((MinBitsPerElt % 8) != 0)
8389       return false;
8390 
8391     // Attempt to find the source vector the scalar was extracted from.
8392     SDValue SrcExtract;
8393     if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
8394          Scl.getOpcode() == X86ISD::PEXTRW ||
8395          Scl.getOpcode() == X86ISD::PEXTRB) &&
8396         Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
8397       SrcExtract = Scl;
8398     }
8399     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
8400       return false;
8401 
8402     SDValue SrcVec = SrcExtract.getOperand(0);
8403     EVT SrcVT = SrcVec.getValueType();
8404     if (!SrcVT.getScalarType().isByteSized())
8405       return false;
8406     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
8407     unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
8408     unsigned DstByte = DstIdx * NumBytesPerElt;
8409     MinBitsPerElt =
8410         std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
8411 
8412     // Create 'identity' byte level shuffle mask and then add inserted bytes.
8413     if (Opcode == ISD::SCALAR_TO_VECTOR) {
8414       Ops.push_back(SrcVec);
8415       Mask.append(NumSizeInBytes, SM_SentinelUndef);
8416     } else {
8417       Ops.push_back(SrcVec);
8418       Ops.push_back(N.getOperand(0));
8419       for (int i = 0; i != (int)NumSizeInBytes; ++i)
8420         Mask.push_back(NumSizeInBytes + i);
8421     }
8422 
8423     unsigned MinBytesPerElts = MinBitsPerElt / 8;
8424     MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
8425     for (unsigned i = 0; i != MinBytesPerElts; ++i)
8426       Mask[DstByte + i] = SrcByte + i;
8427     for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
8428       Mask[DstByte + i] = SM_SentinelZero;
8429     return true;
8430   }
8431   case X86ISD::PACKSS:
8432   case X86ISD::PACKUS: {
8433     SDValue N0 = N.getOperand(0);
8434     SDValue N1 = N.getOperand(1);
8435     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
8436            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
8437            "Unexpected input value type");
8438 
8439     APInt EltsLHS, EltsRHS;
8440     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
8441 
8442     // If we know input saturation won't happen (or we don't care for particular
8443     // lanes), we can treat this as a truncation shuffle.
8444     bool Offset0 = false, Offset1 = false;
8445     if (Opcode == X86ISD::PACKSS) {
8446       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
8447            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
8448           (!(N1.isUndef() || EltsRHS.isZero()) &&
8449            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
8450         return false;
8451       // We can't easily fold ASHR into a shuffle, but if it was feeding a
8452       // PACKSS then it was likely being used for sign-extension for a
8453       // truncation, so just peek through and adjust the mask accordingly.
8454       if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
8455           N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
8456         Offset0 = true;
8457         N0 = N0.getOperand(0);
8458       }
8459       if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
8460           N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
8461         Offset1 = true;
8462         N1 = N1.getOperand(0);
8463       }
8464     } else {
8465       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
8466       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
8467            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
8468           (!(N1.isUndef() || EltsRHS.isZero()) &&
8469            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
8470         return false;
8471     }
8472 
8473     bool IsUnary = (N0 == N1);
8474 
8475     Ops.push_back(N0);
8476     if (!IsUnary)
8477       Ops.push_back(N1);
8478 
8479     createPackShuffleMask(VT, Mask, IsUnary);
8480 
8481     if (Offset0 || Offset1) {
8482       for (int &M : Mask)
8483         if ((Offset0 && isInRange(M, 0, NumElts)) ||
8484             (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
8485           ++M;
8486     }
8487     return true;
8488   }
8489   case ISD::VSELECT:
8490   case X86ISD::BLENDV: {
8491     SDValue Cond = N.getOperand(0);
8492     if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
8493       Ops.push_back(N.getOperand(1));
8494       Ops.push_back(N.getOperand(2));
8495       return true;
8496     }
8497     return false;
8498   }
8499   case X86ISD::VTRUNC: {
8500     SDValue Src = N.getOperand(0);
8501     EVT SrcVT = Src.getValueType();
8502     // Truncated source must be a simple vector.
8503     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8504         (SrcVT.getScalarSizeInBits() % 8) != 0)
8505       return false;
8506     unsigned NumSrcElts = SrcVT.getVectorNumElements();
8507     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
8508     unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
8509     assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
8510     for (unsigned i = 0; i != NumSrcElts; ++i)
8511       Mask.push_back(i * Scale);
8512     Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
8513     Ops.push_back(Src);
8514     return true;
8515   }
8516   case X86ISD::VSHLI:
8517   case X86ISD::VSRLI: {
8518     uint64_t ShiftVal = N.getConstantOperandVal(1);
8519     // Out of range bit shifts are guaranteed to be zero.
8520     if (NumBitsPerElt <= ShiftVal) {
8521       Mask.append(NumElts, SM_SentinelZero);
8522       return true;
8523     }
8524 
8525     // We can only decode 'whole byte' bit shifts as shuffles.
8526     if ((ShiftVal % 8) != 0)
8527       break;
8528 
8529     uint64_t ByteShift = ShiftVal / 8;
8530     Ops.push_back(N.getOperand(0));
8531 
8532     // Clear mask to all zeros and insert the shifted byte indices.
8533     Mask.append(NumSizeInBytes, SM_SentinelZero);
8534 
8535     if (X86ISD::VSHLI == Opcode) {
8536       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
8537         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
8538           Mask[i + j] = i + j - ByteShift;
8539     } else {
8540       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
8541         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
8542           Mask[i + j - ByteShift] = i + j;
8543     }
8544     return true;
8545   }
8546   case X86ISD::VROTLI:
8547   case X86ISD::VROTRI: {
8548     // We can only decode 'whole byte' bit rotates as shuffles.
8549     uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
8550     if ((RotateVal % 8) != 0)
8551       return false;
8552     Ops.push_back(N.getOperand(0));
8553     int Offset = RotateVal / 8;
8554     Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
8555     for (int i = 0; i != (int)NumElts; ++i) {
8556       int BaseIdx = i * NumBytesPerElt;
8557       for (int j = 0; j != (int)NumBytesPerElt; ++j) {
8558         Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
8559       }
8560     }
8561     return true;
8562   }
8563   case X86ISD::VBROADCAST: {
8564     SDValue Src = N.getOperand(0);
8565     if (!Src.getSimpleValueType().isVector()) {
8566       if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8567           !isNullConstant(Src.getOperand(1)) ||
8568           Src.getOperand(0).getValueType().getScalarType() !=
8569               VT.getScalarType())
8570         return false;
8571       Src = Src.getOperand(0);
8572     }
8573     Ops.push_back(Src);
8574     Mask.append(NumElts, 0);
8575     return true;
8576   }
8577   case ISD::ZERO_EXTEND:
8578   case ISD::ANY_EXTEND:
8579   case ISD::ZERO_EXTEND_VECTOR_INREG:
8580   case ISD::ANY_EXTEND_VECTOR_INREG: {
8581     SDValue Src = N.getOperand(0);
8582     EVT SrcVT = Src.getValueType();
8583 
8584     // Extended source must be a simple vector.
8585     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8586         (SrcVT.getScalarSizeInBits() % 8) != 0)
8587       return false;
8588 
8589     bool IsAnyExtend =
8590         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
8591     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
8592                          IsAnyExtend, Mask);
8593     Ops.push_back(Src);
8594     return true;
8595   }
8596   }
8597 
8598   return false;
8599 }
8600 
8601 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
8602 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
8603                                               SmallVectorImpl<int> &Mask) {
8604   int MaskWidth = Mask.size();
8605   SmallVector<SDValue, 16> UsedInputs;
8606   for (int i = 0, e = Inputs.size(); i < e; ++i) {
8607     int lo = UsedInputs.size() * MaskWidth;
8608     int hi = lo + MaskWidth;
8609 
8610     // Strip UNDEF input usage.
8611     if (Inputs[i].isUndef())
8612       for (int &M : Mask)
8613         if ((lo <= M) && (M < hi))
8614           M = SM_SentinelUndef;
8615 
8616     // Check for unused inputs.
8617     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
8618       for (int &M : Mask)
8619         if (lo <= M)
8620           M -= MaskWidth;
8621       continue;
8622     }
8623 
8624     // Check for repeated inputs.
8625     bool IsRepeat = false;
8626     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
8627       if (UsedInputs[j] != Inputs[i])
8628         continue;
8629       for (int &M : Mask)
8630         if (lo <= M)
8631           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
8632       IsRepeat = true;
8633       break;
8634     }
8635     if (IsRepeat)
8636       continue;
8637 
8638     UsedInputs.push_back(Inputs[i]);
8639   }
8640   Inputs = UsedInputs;
8641 }
8642 
8643 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
8644 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
8645 /// Returns true if the target shuffle mask was decoded.
8646 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
8647                                    SmallVectorImpl<SDValue> &Inputs,
8648                                    SmallVectorImpl<int> &Mask,
8649                                    APInt &KnownUndef, APInt &KnownZero,
8650                                    const SelectionDAG &DAG, unsigned Depth,
8651                                    bool ResolveKnownElts) {
8652   if (Depth >= SelectionDAG::MaxRecursionDepth)
8653     return false; // Limit search depth.
8654 
8655   EVT VT = Op.getValueType();
8656   if (!VT.isSimple() || !VT.isVector())
8657     return false;
8658 
8659   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
8660     if (ResolveKnownElts)
8661       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
8662     return true;
8663   }
8664   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
8665                          ResolveKnownElts)) {
8666     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
8667     return true;
8668   }
8669   return false;
8670 }
8671 
8672 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
8673                                    SmallVectorImpl<int> &Mask,
8674                                    const SelectionDAG &DAG, unsigned Depth = 0,
8675                                    bool ResolveKnownElts = true) {
8676   EVT VT = Op.getValueType();
8677   if (!VT.isSimple() || !VT.isVector())
8678     return false;
8679 
8680   APInt KnownUndef, KnownZero;
8681   unsigned NumElts = Op.getValueType().getVectorNumElements();
8682   APInt DemandedElts = APInt::getAllOnes(NumElts);
8683   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
8684                                 KnownZero, DAG, Depth, ResolveKnownElts);
8685 }
8686 
8687 // Attempt to create a scalar/subvector broadcast from the base MemSDNode.
8688 static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
8689                                  EVT MemVT, MemSDNode *Mem, unsigned Offset,
8690                                  SelectionDAG &DAG) {
8691   assert((Opcode == X86ISD::VBROADCAST_LOAD ||
8692           Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
8693          "Unknown broadcast load type");
8694 
8695   // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
8696   if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
8697     return SDValue();
8698 
8699   SDValue Ptr =
8700       DAG.getMemBasePlusOffset(Mem->getBasePtr(), TypeSize::Fixed(Offset), DL);
8701   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8702   SDValue Ops[] = {Mem->getChain(), Ptr};
8703   SDValue BcstLd = DAG.getMemIntrinsicNode(
8704       Opcode, DL, Tys, Ops, MemVT,
8705       DAG.getMachineFunction().getMachineMemOperand(
8706           Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
8707   DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
8708   return BcstLd;
8709 }
8710 
8711 /// Returns the scalar element that will make up the i'th
8712 /// element of the result of the vector shuffle.
8713 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
8714                                    SelectionDAG &DAG, unsigned Depth) {
8715   if (Depth >= SelectionDAG::MaxRecursionDepth)
8716     return SDValue(); // Limit search depth.
8717 
8718   EVT VT = Op.getValueType();
8719   unsigned Opcode = Op.getOpcode();
8720   unsigned NumElems = VT.getVectorNumElements();
8721 
8722   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
8723   if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
8724     int Elt = SV->getMaskElt(Index);
8725 
8726     if (Elt < 0)
8727       return DAG.getUNDEF(VT.getVectorElementType());
8728 
8729     SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
8730     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
8731   }
8732 
8733   // Recurse into target specific vector shuffles to find scalars.
8734   if (isTargetShuffle(Opcode)) {
8735     MVT ShufVT = VT.getSimpleVT();
8736     MVT ShufSVT = ShufVT.getVectorElementType();
8737     int NumElems = (int)ShufVT.getVectorNumElements();
8738     SmallVector<int, 16> ShuffleMask;
8739     SmallVector<SDValue, 16> ShuffleOps;
8740     if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
8741                               ShuffleMask))
8742       return SDValue();
8743 
8744     int Elt = ShuffleMask[Index];
8745     if (Elt == SM_SentinelZero)
8746       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
8747                                  : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
8748     if (Elt == SM_SentinelUndef)
8749       return DAG.getUNDEF(ShufSVT);
8750 
8751     assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
8752     SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
8753     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
8754   }
8755 
8756   // Recurse into insert_subvector base/sub vector to find scalars.
8757   if (Opcode == ISD::INSERT_SUBVECTOR) {
8758     SDValue Vec = Op.getOperand(0);
8759     SDValue Sub = Op.getOperand(1);
8760     uint64_t SubIdx = Op.getConstantOperandVal(2);
8761     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
8762 
8763     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
8764       return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
8765     return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
8766   }
8767 
8768   // Recurse into concat_vectors sub vector to find scalars.
8769   if (Opcode == ISD::CONCAT_VECTORS) {
8770     EVT SubVT = Op.getOperand(0).getValueType();
8771     unsigned NumSubElts = SubVT.getVectorNumElements();
8772     uint64_t SubIdx = Index / NumSubElts;
8773     uint64_t SubElt = Index % NumSubElts;
8774     return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
8775   }
8776 
8777   // Recurse into extract_subvector src vector to find scalars.
8778   if (Opcode == ISD::EXTRACT_SUBVECTOR) {
8779     SDValue Src = Op.getOperand(0);
8780     uint64_t SrcIdx = Op.getConstantOperandVal(1);
8781     return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
8782   }
8783 
8784   // We only peek through bitcasts of the same vector width.
8785   if (Opcode == ISD::BITCAST) {
8786     SDValue Src = Op.getOperand(0);
8787     EVT SrcVT = Src.getValueType();
8788     if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
8789       return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
8790     return SDValue();
8791   }
8792 
8793   // Actual nodes that may contain scalar elements
8794 
8795   // For insert_vector_elt - either return the index matching scalar or recurse
8796   // into the base vector.
8797   if (Opcode == ISD::INSERT_VECTOR_ELT &&
8798       isa<ConstantSDNode>(Op.getOperand(2))) {
8799     if (Op.getConstantOperandAPInt(2) == Index)
8800       return Op.getOperand(1);
8801     return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
8802   }
8803 
8804   if (Opcode == ISD::SCALAR_TO_VECTOR)
8805     return (Index == 0) ? Op.getOperand(0)
8806                         : DAG.getUNDEF(VT.getVectorElementType());
8807 
8808   if (Opcode == ISD::BUILD_VECTOR)
8809     return Op.getOperand(Index);
8810 
8811   return SDValue();
8812 }
8813 
8814 // Use PINSRB/PINSRW/PINSRD to create a build vector.
8815 static SDValue LowerBuildVectorAsInsert(SDValue Op, const APInt &NonZeroMask,
8816                                         unsigned NumNonZero, unsigned NumZero,
8817                                         SelectionDAG &DAG,
8818                                         const X86Subtarget &Subtarget) {
8819   MVT VT = Op.getSimpleValueType();
8820   unsigned NumElts = VT.getVectorNumElements();
8821   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
8822           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
8823          "Illegal vector insertion");
8824 
8825   SDLoc dl(Op);
8826   SDValue V;
8827   bool First = true;
8828 
8829   for (unsigned i = 0; i < NumElts; ++i) {
8830     bool IsNonZero = NonZeroMask[i];
8831     if (!IsNonZero)
8832       continue;
8833 
8834     // If the build vector contains zeros or our first insertion is not the
8835     // first index then insert into zero vector to break any register
8836     // dependency else use SCALAR_TO_VECTOR.
8837     if (First) {
8838       First = false;
8839       if (NumZero || 0 != i)
8840         V = getZeroVector(VT, Subtarget, DAG, dl);
8841       else {
8842         assert(0 == i && "Expected insertion into zero-index");
8843         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8844         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
8845         V = DAG.getBitcast(VT, V);
8846         continue;
8847       }
8848     }
8849     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
8850                     DAG.getIntPtrConstant(i, dl));
8851   }
8852 
8853   return V;
8854 }
8855 
8856 /// Custom lower build_vector of v16i8.
8857 static SDValue LowerBuildVectorv16i8(SDValue Op, const APInt &NonZeroMask,
8858                                      unsigned NumNonZero, unsigned NumZero,
8859                                      SelectionDAG &DAG,
8860                                      const X86Subtarget &Subtarget) {
8861   if (NumNonZero > 8 && !Subtarget.hasSSE41())
8862     return SDValue();
8863 
8864   // SSE4.1 - use PINSRB to insert each byte directly.
8865   if (Subtarget.hasSSE41())
8866     return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8867                                     Subtarget);
8868 
8869   SDLoc dl(Op);
8870   SDValue V;
8871 
8872   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
8873   for (unsigned i = 0; i < 16; i += 2) {
8874     bool ThisIsNonZero = NonZeroMask[i];
8875     bool NextIsNonZero = NonZeroMask[i + 1];
8876     if (!ThisIsNonZero && !NextIsNonZero)
8877       continue;
8878 
8879     // FIXME: Investigate combining the first 4 bytes as a i32 instead.
8880     SDValue Elt;
8881     if (ThisIsNonZero) {
8882       if (NumZero || NextIsNonZero)
8883         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8884       else
8885         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8886     }
8887 
8888     if (NextIsNonZero) {
8889       SDValue NextElt = Op.getOperand(i + 1);
8890       if (i == 0 && NumZero)
8891         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
8892       else
8893         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
8894       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
8895                             DAG.getConstant(8, dl, MVT::i8));
8896       if (ThisIsNonZero)
8897         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
8898       else
8899         Elt = NextElt;
8900     }
8901 
8902     // If our first insertion is not the first index or zeros are needed, then
8903     // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
8904     // elements undefined).
8905     if (!V) {
8906       if (i != 0 || NumZero)
8907         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
8908       else {
8909         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
8910         V = DAG.getBitcast(MVT::v8i16, V);
8911         continue;
8912       }
8913     }
8914     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
8915     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
8916                     DAG.getIntPtrConstant(i / 2, dl));
8917   }
8918 
8919   return DAG.getBitcast(MVT::v16i8, V);
8920 }
8921 
8922 /// Custom lower build_vector of v8i16.
8923 static SDValue LowerBuildVectorv8i16(SDValue Op, const APInt &NonZeroMask,
8924                                      unsigned NumNonZero, unsigned NumZero,
8925                                      SelectionDAG &DAG,
8926                                      const X86Subtarget &Subtarget) {
8927   if (NumNonZero > 4 && !Subtarget.hasSSE41())
8928     return SDValue();
8929 
8930   // Use PINSRW to insert each byte directly.
8931   return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8932                                   Subtarget);
8933 }
8934 
8935 /// Custom lower build_vector of v4i32 or v4f32.
8936 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
8937                                      const X86Subtarget &Subtarget) {
8938   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
8939   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
8940   // Because we're creating a less complicated build vector here, we may enable
8941   // further folding of the MOVDDUP via shuffle transforms.
8942   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
8943       Op.getOperand(0) == Op.getOperand(2) &&
8944       Op.getOperand(1) == Op.getOperand(3) &&
8945       Op.getOperand(0) != Op.getOperand(1)) {
8946     SDLoc DL(Op);
8947     MVT VT = Op.getSimpleValueType();
8948     MVT EltVT = VT.getVectorElementType();
8949     // Create a new build vector with the first 2 elements followed by undef
8950     // padding, bitcast to v2f64, duplicate, and bitcast back.
8951     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
8952                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
8953     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
8954     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
8955     return DAG.getBitcast(VT, Dup);
8956   }
8957 
8958   // Find all zeroable elements.
8959   std::bitset<4> Zeroable, Undefs;
8960   for (int i = 0; i < 4; ++i) {
8961     SDValue Elt = Op.getOperand(i);
8962     Undefs[i] = Elt.isUndef();
8963     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
8964   }
8965   assert(Zeroable.size() - Zeroable.count() > 1 &&
8966          "We expect at least two non-zero elements!");
8967 
8968   // We only know how to deal with build_vector nodes where elements are either
8969   // zeroable or extract_vector_elt with constant index.
8970   SDValue FirstNonZero;
8971   unsigned FirstNonZeroIdx;
8972   for (unsigned i = 0; i < 4; ++i) {
8973     if (Zeroable[i])
8974       continue;
8975     SDValue Elt = Op.getOperand(i);
8976     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8977         !isa<ConstantSDNode>(Elt.getOperand(1)))
8978       return SDValue();
8979     // Make sure that this node is extracting from a 128-bit vector.
8980     MVT VT = Elt.getOperand(0).getSimpleValueType();
8981     if (!VT.is128BitVector())
8982       return SDValue();
8983     if (!FirstNonZero.getNode()) {
8984       FirstNonZero = Elt;
8985       FirstNonZeroIdx = i;
8986     }
8987   }
8988 
8989   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
8990   SDValue V1 = FirstNonZero.getOperand(0);
8991   MVT VT = V1.getSimpleValueType();
8992 
8993   // See if this build_vector can be lowered as a blend with zero.
8994   SDValue Elt;
8995   unsigned EltMaskIdx, EltIdx;
8996   int Mask[4];
8997   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
8998     if (Zeroable[EltIdx]) {
8999       // The zero vector will be on the right hand side.
9000       Mask[EltIdx] = EltIdx+4;
9001       continue;
9002     }
9003 
9004     Elt = Op->getOperand(EltIdx);
9005     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
9006     EltMaskIdx = Elt.getConstantOperandVal(1);
9007     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
9008       break;
9009     Mask[EltIdx] = EltIdx;
9010   }
9011 
9012   if (EltIdx == 4) {
9013     // Let the shuffle legalizer deal with blend operations.
9014     SDValue VZeroOrUndef = (Zeroable == Undefs)
9015                                ? DAG.getUNDEF(VT)
9016                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
9017     if (V1.getSimpleValueType() != VT)
9018       V1 = DAG.getBitcast(VT, V1);
9019     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
9020   }
9021 
9022   // See if we can lower this build_vector to a INSERTPS.
9023   if (!Subtarget.hasSSE41())
9024     return SDValue();
9025 
9026   SDValue V2 = Elt.getOperand(0);
9027   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
9028     V1 = SDValue();
9029 
9030   bool CanFold = true;
9031   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
9032     if (Zeroable[i])
9033       continue;
9034 
9035     SDValue Current = Op->getOperand(i);
9036     SDValue SrcVector = Current->getOperand(0);
9037     if (!V1.getNode())
9038       V1 = SrcVector;
9039     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
9040   }
9041 
9042   if (!CanFold)
9043     return SDValue();
9044 
9045   assert(V1.getNode() && "Expected at least two non-zero elements!");
9046   if (V1.getSimpleValueType() != MVT::v4f32)
9047     V1 = DAG.getBitcast(MVT::v4f32, V1);
9048   if (V2.getSimpleValueType() != MVT::v4f32)
9049     V2 = DAG.getBitcast(MVT::v4f32, V2);
9050 
9051   // Ok, we can emit an INSERTPS instruction.
9052   unsigned ZMask = Zeroable.to_ulong();
9053 
9054   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
9055   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
9056   SDLoc DL(Op);
9057   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
9058                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
9059   return DAG.getBitcast(VT, Result);
9060 }
9061 
9062 /// Return a vector logical shift node.
9063 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
9064                          SelectionDAG &DAG, const TargetLowering &TLI,
9065                          const SDLoc &dl) {
9066   assert(VT.is128BitVector() && "Unknown type for VShift");
9067   MVT ShVT = MVT::v16i8;
9068   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
9069   SrcOp = DAG.getBitcast(ShVT, SrcOp);
9070   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
9071   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
9072   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
9073 }
9074 
9075 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
9076                                       SelectionDAG &DAG) {
9077 
9078   // Check if the scalar load can be widened into a vector load. And if
9079   // the address is "base + cst" see if the cst can be "absorbed" into
9080   // the shuffle mask.
9081   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
9082     SDValue Ptr = LD->getBasePtr();
9083     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
9084       return SDValue();
9085     EVT PVT = LD->getValueType(0);
9086     if (PVT != MVT::i32 && PVT != MVT::f32)
9087       return SDValue();
9088 
9089     int FI = -1;
9090     int64_t Offset = 0;
9091     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
9092       FI = FINode->getIndex();
9093       Offset = 0;
9094     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
9095                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9096       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9097       Offset = Ptr.getConstantOperandVal(1);
9098       Ptr = Ptr.getOperand(0);
9099     } else {
9100       return SDValue();
9101     }
9102 
9103     // FIXME: 256-bit vector instructions don't require a strict alignment,
9104     // improve this code to support it better.
9105     Align RequiredAlign(VT.getSizeInBits() / 8);
9106     SDValue Chain = LD->getChain();
9107     // Make sure the stack object alignment is at least 16 or 32.
9108     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9109     MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
9110     if (!InferredAlign || *InferredAlign < RequiredAlign) {
9111       if (MFI.isFixedObjectIndex(FI)) {
9112         // Can't change the alignment. FIXME: It's possible to compute
9113         // the exact stack offset and reference FI + adjust offset instead.
9114         // If someone *really* cares about this. That's the way to implement it.
9115         return SDValue();
9116       } else {
9117         MFI.setObjectAlignment(FI, RequiredAlign);
9118       }
9119     }
9120 
9121     // (Offset % 16 or 32) must be multiple of 4. Then address is then
9122     // Ptr + (Offset & ~15).
9123     if (Offset < 0)
9124       return SDValue();
9125     if ((Offset % RequiredAlign.value()) & 3)
9126       return SDValue();
9127     int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
9128     if (StartOffset) {
9129       SDLoc DL(Ptr);
9130       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
9131                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
9132     }
9133 
9134     int EltNo = (Offset - StartOffset) >> 2;
9135     unsigned NumElems = VT.getVectorNumElements();
9136 
9137     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
9138     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
9139                              LD->getPointerInfo().getWithOffset(StartOffset));
9140 
9141     SmallVector<int, 8> Mask(NumElems, EltNo);
9142 
9143     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
9144   }
9145 
9146   return SDValue();
9147 }
9148 
9149 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
9150 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
9151   if (ISD::isNON_EXTLoad(Elt.getNode())) {
9152     auto *BaseLd = cast<LoadSDNode>(Elt);
9153     if (!BaseLd->isSimple())
9154       return false;
9155     Ld = BaseLd;
9156     ByteOffset = 0;
9157     return true;
9158   }
9159 
9160   switch (Elt.getOpcode()) {
9161   case ISD::BITCAST:
9162   case ISD::TRUNCATE:
9163   case ISD::SCALAR_TO_VECTOR:
9164     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
9165   case ISD::SRL:
9166     if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
9167       uint64_t Amt = AmtC->getZExtValue();
9168       if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
9169         ByteOffset += Amt / 8;
9170         return true;
9171       }
9172     }
9173     break;
9174   case ISD::EXTRACT_VECTOR_ELT:
9175     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
9176       SDValue Src = Elt.getOperand(0);
9177       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
9178       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
9179       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
9180           findEltLoadSrc(Src, Ld, ByteOffset)) {
9181         uint64_t Idx = IdxC->getZExtValue();
9182         ByteOffset += Idx * (SrcSizeInBits / 8);
9183         return true;
9184       }
9185     }
9186     break;
9187   }
9188 
9189   return false;
9190 }
9191 
9192 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
9193 /// elements can be replaced by a single large load which has the same value as
9194 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
9195 ///
9196 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
9197 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
9198                                         const SDLoc &DL, SelectionDAG &DAG,
9199                                         const X86Subtarget &Subtarget,
9200                                         bool IsAfterLegalize) {
9201   if ((VT.getScalarSizeInBits() % 8) != 0)
9202     return SDValue();
9203 
9204   unsigned NumElems = Elts.size();
9205 
9206   int LastLoadedElt = -1;
9207   APInt LoadMask = APInt::getZero(NumElems);
9208   APInt ZeroMask = APInt::getZero(NumElems);
9209   APInt UndefMask = APInt::getZero(NumElems);
9210 
9211   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
9212   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
9213 
9214   // For each element in the initializer, see if we've found a load, zero or an
9215   // undef.
9216   for (unsigned i = 0; i < NumElems; ++i) {
9217     SDValue Elt = peekThroughBitcasts(Elts[i]);
9218     if (!Elt.getNode())
9219       return SDValue();
9220     if (Elt.isUndef()) {
9221       UndefMask.setBit(i);
9222       continue;
9223     }
9224     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
9225       ZeroMask.setBit(i);
9226       continue;
9227     }
9228 
9229     // Each loaded element must be the correct fractional portion of the
9230     // requested vector load.
9231     unsigned EltSizeInBits = Elt.getValueSizeInBits();
9232     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
9233       return SDValue();
9234 
9235     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
9236       return SDValue();
9237     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
9238     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
9239       return SDValue();
9240 
9241     LoadMask.setBit(i);
9242     LastLoadedElt = i;
9243   }
9244   assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +
9245           LoadMask.countPopulation()) == NumElems &&
9246          "Incomplete element masks");
9247 
9248   // Handle Special Cases - all undef or undef/zero.
9249   if (UndefMask.countPopulation() == NumElems)
9250     return DAG.getUNDEF(VT);
9251   if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
9252     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
9253                           : DAG.getConstantFP(0.0, DL, VT);
9254 
9255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9256   int FirstLoadedElt = LoadMask.countTrailingZeros();
9257   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
9258   EVT EltBaseVT = EltBase.getValueType();
9259   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
9260          "Register/Memory size mismatch");
9261   LoadSDNode *LDBase = Loads[FirstLoadedElt];
9262   assert(LDBase && "Did not find base load for merging consecutive loads");
9263   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
9264   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
9265   int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
9266   int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
9267   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
9268 
9269   // TODO: Support offsetting the base load.
9270   if (ByteOffsets[FirstLoadedElt] != 0)
9271     return SDValue();
9272 
9273   // Check to see if the element's load is consecutive to the base load
9274   // or offset from a previous (already checked) load.
9275   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
9276     LoadSDNode *Ld = Loads[EltIdx];
9277     int64_t ByteOffset = ByteOffsets[EltIdx];
9278     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
9279       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
9280       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
9281               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
9282     }
9283     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
9284                                               EltIdx - FirstLoadedElt);
9285   };
9286 
9287   // Consecutive loads can contain UNDEFS but not ZERO elements.
9288   // Consecutive loads with UNDEFs and ZEROs elements require a
9289   // an additional shuffle stage to clear the ZERO elements.
9290   bool IsConsecutiveLoad = true;
9291   bool IsConsecutiveLoadWithZeros = true;
9292   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
9293     if (LoadMask[i]) {
9294       if (!CheckConsecutiveLoad(LDBase, i)) {
9295         IsConsecutiveLoad = false;
9296         IsConsecutiveLoadWithZeros = false;
9297         break;
9298       }
9299     } else if (ZeroMask[i]) {
9300       IsConsecutiveLoad = false;
9301     }
9302   }
9303 
9304   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
9305     auto MMOFlags = LDBase->getMemOperand()->getFlags();
9306     assert(LDBase->isSimple() &&
9307            "Cannot merge volatile or atomic loads.");
9308     SDValue NewLd =
9309         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
9310                     LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
9311                     MMOFlags);
9312     for (auto *LD : Loads)
9313       if (LD)
9314         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
9315     return NewLd;
9316   };
9317 
9318   // Check if the base load is entirely dereferenceable.
9319   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
9320       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
9321 
9322   // LOAD - all consecutive load/undefs (must start/end with a load or be
9323   // entirely dereferenceable). If we have found an entire vector of loads and
9324   // undefs, then return a large load of the entire vector width starting at the
9325   // base pointer. If the vector contains zeros, then attempt to shuffle those
9326   // elements.
9327   if (FirstLoadedElt == 0 &&
9328       (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
9329       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
9330     if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
9331       return SDValue();
9332 
9333     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
9334     // will lower to regular temporal loads and use the cache.
9335     if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
9336         VT.is256BitVector() && !Subtarget.hasInt256())
9337       return SDValue();
9338 
9339     if (NumElems == 1)
9340       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
9341 
9342     if (!ZeroMask)
9343       return CreateLoad(VT, LDBase);
9344 
9345     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
9346     // vector and a zero vector to clear out the zero elements.
9347     if (!IsAfterLegalize && VT.isVector()) {
9348       unsigned NumMaskElts = VT.getVectorNumElements();
9349       if ((NumMaskElts % NumElems) == 0) {
9350         unsigned Scale = NumMaskElts / NumElems;
9351         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
9352         for (unsigned i = 0; i < NumElems; ++i) {
9353           if (UndefMask[i])
9354             continue;
9355           int Offset = ZeroMask[i] ? NumMaskElts : 0;
9356           for (unsigned j = 0; j != Scale; ++j)
9357             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
9358         }
9359         SDValue V = CreateLoad(VT, LDBase);
9360         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
9361                                    : DAG.getConstantFP(0.0, DL, VT);
9362         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
9363       }
9364     }
9365   }
9366 
9367   // If the upper half of a ymm/zmm load is undef then just load the lower half.
9368   if (VT.is256BitVector() || VT.is512BitVector()) {
9369     unsigned HalfNumElems = NumElems / 2;
9370     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
9371       EVT HalfVT =
9372           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
9373       SDValue HalfLD =
9374           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
9375                                    DAG, Subtarget, IsAfterLegalize);
9376       if (HalfLD)
9377         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
9378                            HalfLD, DAG.getIntPtrConstant(0, DL));
9379     }
9380   }
9381 
9382   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
9383   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
9384       ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
9385        LoadSizeInBits == 64) &&
9386       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
9387     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
9388                                       : MVT::getIntegerVT(LoadSizeInBits);
9389     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
9390     // Allow v4f32 on SSE1 only targets.
9391     // FIXME: Add more isel patterns so we can just use VT directly.
9392     if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
9393       VecVT = MVT::v4f32;
9394     if (TLI.isTypeLegal(VecVT)) {
9395       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
9396       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
9397       SDValue ResNode = DAG.getMemIntrinsicNode(
9398           X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
9399           LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
9400       for (auto *LD : Loads)
9401         if (LD)
9402           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
9403       return DAG.getBitcast(VT, ResNode);
9404     }
9405   }
9406 
9407   // BROADCAST - match the smallest possible repetition pattern, load that
9408   // scalar/subvector element and then broadcast to the entire vector.
9409   if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
9410       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
9411     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
9412       unsigned RepeatSize = SubElems * BaseSizeInBits;
9413       unsigned ScalarSize = std::min(RepeatSize, 64u);
9414       if (!Subtarget.hasAVX2() && ScalarSize < 32)
9415         continue;
9416 
9417       // Don't attempt a 1:N subvector broadcast - it should be caught by
9418       // combineConcatVectorOps, else will cause infinite loops.
9419       if (RepeatSize > ScalarSize && SubElems == 1)
9420         continue;
9421 
9422       bool Match = true;
9423       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
9424       for (unsigned i = 0; i != NumElems && Match; ++i) {
9425         if (!LoadMask[i])
9426           continue;
9427         SDValue Elt = peekThroughBitcasts(Elts[i]);
9428         if (RepeatedLoads[i % SubElems].isUndef())
9429           RepeatedLoads[i % SubElems] = Elt;
9430         else
9431           Match &= (RepeatedLoads[i % SubElems] == Elt);
9432       }
9433 
9434       // We must have loads at both ends of the repetition.
9435       Match &= !RepeatedLoads.front().isUndef();
9436       Match &= !RepeatedLoads.back().isUndef();
9437       if (!Match)
9438         continue;
9439 
9440       EVT RepeatVT =
9441           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
9442               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
9443               : EVT::getFloatingPointVT(ScalarSize);
9444       if (RepeatSize > ScalarSize)
9445         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
9446                                     RepeatSize / ScalarSize);
9447       EVT BroadcastVT =
9448           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
9449                            VT.getSizeInBits() / ScalarSize);
9450       if (TLI.isTypeLegal(BroadcastVT)) {
9451         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
9452                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize)) {
9453           SDValue Broadcast = RepeatLoad;
9454           if (RepeatSize > ScalarSize) {
9455             while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
9456               Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
9457           } else {
9458             if (!Subtarget.hasAVX2() &&
9459                 !X86::mayFoldLoadIntoBroadcastFromMem(
9460                     RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
9461                     Subtarget,
9462                     /*AssumeSingleUse=*/true))
9463               return SDValue();
9464             Broadcast =
9465                 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
9466           }
9467           return DAG.getBitcast(VT, Broadcast);
9468         }
9469       }
9470     }
9471   }
9472 
9473   return SDValue();
9474 }
9475 
9476 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
9477 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
9478 // are consecutive, non-overlapping, and in the right order.
9479 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
9480                                          SelectionDAG &DAG,
9481                                          const X86Subtarget &Subtarget,
9482                                          bool IsAfterLegalize) {
9483   SmallVector<SDValue, 64> Elts;
9484   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9485     if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
9486       Elts.push_back(Elt);
9487       continue;
9488     }
9489     return SDValue();
9490   }
9491   assert(Elts.size() == VT.getVectorNumElements());
9492   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
9493                                   IsAfterLegalize);
9494 }
9495 
9496 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
9497                                    unsigned SplatBitSize, LLVMContext &C) {
9498   unsigned ScalarSize = VT.getScalarSizeInBits();
9499   unsigned NumElm = SplatBitSize / ScalarSize;
9500 
9501   SmallVector<Constant *, 32> ConstantVec;
9502   for (unsigned i = 0; i < NumElm; i++) {
9503     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
9504     Constant *Const;
9505     if (VT.isFloatingPoint()) {
9506       if (ScalarSize == 16) {
9507         Const = ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
9508       } else if (ScalarSize == 32) {
9509         Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
9510       } else {
9511         assert(ScalarSize == 64 && "Unsupported floating point scalar size");
9512         Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
9513       }
9514     } else
9515       Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
9516     ConstantVec.push_back(Const);
9517   }
9518   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
9519 }
9520 
9521 static bool isFoldableUseOfShuffle(SDNode *N) {
9522   for (auto *U : N->uses()) {
9523     unsigned Opc = U->getOpcode();
9524     // VPERMV/VPERMV3 shuffles can never fold their index operands.
9525     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
9526       return false;
9527     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
9528       return false;
9529     if (isTargetShuffle(Opc))
9530       return true;
9531     if (Opc == ISD::BITCAST) // Ignore bitcasts
9532       return isFoldableUseOfShuffle(U);
9533     if (N->hasOneUse()) {
9534       // TODO, there may be some general way to know if a SDNode can
9535       // be folded. We now only know whether an MI is foldable.
9536       if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
9537         return false;
9538       return true;
9539     }
9540   }
9541   return false;
9542 }
9543 
9544 /// Attempt to use the vbroadcast instruction to generate a splat value
9545 /// from a splat BUILD_VECTOR which uses:
9546 ///  a. A single scalar load, or a constant.
9547 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
9548 ///
9549 /// The VBROADCAST node is returned when a pattern is found,
9550 /// or SDValue() otherwise.
9551 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
9552                                            const X86Subtarget &Subtarget,
9553                                            SelectionDAG &DAG) {
9554   // VBROADCAST requires AVX.
9555   // TODO: Splats could be generated for non-AVX CPUs using SSE
9556   // instructions, but there's less potential gain for only 128-bit vectors.
9557   if (!Subtarget.hasAVX())
9558     return SDValue();
9559 
9560   MVT VT = BVOp->getSimpleValueType(0);
9561   unsigned NumElts = VT.getVectorNumElements();
9562   SDLoc dl(BVOp);
9563 
9564   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
9565          "Unsupported vector type for broadcast.");
9566 
9567   // See if the build vector is a repeating sequence of scalars (inc. splat).
9568   SDValue Ld;
9569   BitVector UndefElements;
9570   SmallVector<SDValue, 16> Sequence;
9571   if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
9572     assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
9573     if (Sequence.size() == 1)
9574       Ld = Sequence[0];
9575   }
9576 
9577   // Attempt to use VBROADCASTM
9578   // From this pattern:
9579   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
9580   // b. t1 = (build_vector t0 t0)
9581   //
9582   // Create (VBROADCASTM v2i1 X)
9583   if (!Sequence.empty() && Subtarget.hasCDI()) {
9584     // If not a splat, are the upper sequence values zeroable?
9585     unsigned SeqLen = Sequence.size();
9586     bool UpperZeroOrUndef =
9587         SeqLen == 1 ||
9588         llvm::all_of(makeArrayRef(Sequence).drop_front(), [](SDValue V) {
9589           return !V || V.isUndef() || isNullConstant(V);
9590         });
9591     SDValue Op0 = Sequence[0];
9592     if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
9593                              (Op0.getOpcode() == ISD::ZERO_EXTEND &&
9594                               Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
9595       SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
9596                              ? Op0.getOperand(0)
9597                              : Op0.getOperand(0).getOperand(0);
9598       MVT MaskVT = BOperand.getSimpleValueType();
9599       MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
9600       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) ||  // for broadcastmb2q
9601           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
9602         MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
9603         if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
9604           unsigned Scale = 512 / VT.getSizeInBits();
9605           BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
9606         }
9607         SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
9608         if (BcstVT.getSizeInBits() != VT.getSizeInBits())
9609           Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
9610         return DAG.getBitcast(VT, Bcst);
9611       }
9612     }
9613   }
9614 
9615   unsigned NumUndefElts = UndefElements.count();
9616   if (!Ld || (NumElts - NumUndefElts) <= 1) {
9617     APInt SplatValue, Undef;
9618     unsigned SplatBitSize;
9619     bool HasUndef;
9620     // Check if this is a repeated constant pattern suitable for broadcasting.
9621     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
9622         SplatBitSize > VT.getScalarSizeInBits() &&
9623         SplatBitSize < VT.getSizeInBits()) {
9624       // Avoid replacing with broadcast when it's a use of a shuffle
9625       // instruction to preserve the present custom lowering of shuffles.
9626       if (isFoldableUseOfShuffle(BVOp))
9627         return SDValue();
9628       // replace BUILD_VECTOR with broadcast of the repeated constants.
9629       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9630       LLVMContext *Ctx = DAG.getContext();
9631       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
9632       if (Subtarget.hasAVX()) {
9633         if (SplatBitSize == 32 || SplatBitSize == 64 ||
9634             (SplatBitSize < 32 && Subtarget.hasAVX2())) {
9635           // Splatted value can fit in one INTEGER constant in constant pool.
9636           // Load the constant and broadcast it.
9637           MVT CVT = MVT::getIntegerVT(SplatBitSize);
9638           Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
9639           Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
9640           SDValue CP = DAG.getConstantPool(C, PVT);
9641           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
9642 
9643           Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
9644           SDVTList Tys =
9645               DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
9646           SDValue Ops[] = {DAG.getEntryNode(), CP};
9647           MachinePointerInfo MPI =
9648               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9649           SDValue Brdcst = DAG.getMemIntrinsicNode(
9650               X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT, MPI, Alignment,
9651               MachineMemOperand::MOLoad);
9652           return DAG.getBitcast(VT, Brdcst);
9653         }
9654         if (SplatBitSize > 64) {
9655           // Load the vector of constants and broadcast it.
9656           Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
9657                                              *Ctx);
9658           SDValue VCP = DAG.getConstantPool(VecC, PVT);
9659           unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
9660           MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
9661           Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
9662           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9663           SDValue Ops[] = {DAG.getEntryNode(), VCP};
9664           MachinePointerInfo MPI =
9665               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9666           return DAG.getMemIntrinsicNode(
9667               X86ISD::SUBV_BROADCAST_LOAD, dl, Tys, Ops, VVT, MPI, Alignment,
9668               MachineMemOperand::MOLoad);
9669         }
9670       }
9671     }
9672 
9673     // If we are moving a scalar into a vector (Ld must be set and all elements
9674     // but 1 are undef) and that operation is not obviously supported by
9675     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
9676     // That's better than general shuffling and may eliminate a load to GPR and
9677     // move from scalar to vector register.
9678     if (!Ld || NumElts - NumUndefElts != 1)
9679       return SDValue();
9680     unsigned ScalarSize = Ld.getValueSizeInBits();
9681     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
9682       return SDValue();
9683   }
9684 
9685   bool ConstSplatVal =
9686       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
9687   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
9688 
9689   // TODO: Handle broadcasts of non-constant sequences.
9690 
9691   // Make sure that all of the users of a non-constant load are from the
9692   // BUILD_VECTOR node.
9693   // FIXME: Is the use count needed for non-constant, non-load case?
9694   if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
9695     return SDValue();
9696 
9697   unsigned ScalarSize = Ld.getValueSizeInBits();
9698   bool IsGE256 = (VT.getSizeInBits() >= 256);
9699 
9700   // When optimizing for size, generate up to 5 extra bytes for a broadcast
9701   // instruction to save 8 or more bytes of constant pool data.
9702   // TODO: If multiple splats are generated to load the same constant,
9703   // it may be detrimental to overall size. There needs to be a way to detect
9704   // that condition to know if this is truly a size win.
9705   bool OptForSize = DAG.shouldOptForSize();
9706 
9707   // Handle broadcasting a single constant scalar from the constant pool
9708   // into a vector.
9709   // On Sandybridge (no AVX2), it is still better to load a constant vector
9710   // from the constant pool and not to broadcast it from a scalar.
9711   // But override that restriction when optimizing for size.
9712   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
9713   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
9714     EVT CVT = Ld.getValueType();
9715     assert(!CVT.isVector() && "Must not broadcast a vector type");
9716 
9717     // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
9718     // For size optimization, also splat v2f64 and v2i64, and for size opt
9719     // with AVX2, also splat i8 and i16.
9720     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
9721     if (ScalarSize == 32 ||
9722         (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
9723         CVT == MVT::f16 ||
9724         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
9725       const Constant *C = nullptr;
9726       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
9727         C = CI->getConstantIntValue();
9728       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
9729         C = CF->getConstantFPValue();
9730 
9731       assert(C && "Invalid constant type");
9732 
9733       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9734       SDValue CP =
9735           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
9736       Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
9737 
9738       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9739       SDValue Ops[] = {DAG.getEntryNode(), CP};
9740       MachinePointerInfo MPI =
9741           MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9742       return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
9743                                      MPI, Alignment, MachineMemOperand::MOLoad);
9744     }
9745   }
9746 
9747   // Handle AVX2 in-register broadcasts.
9748   if (!IsLoad && Subtarget.hasInt256() &&
9749       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
9750     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
9751 
9752   // The scalar source must be a normal load.
9753   if (!IsLoad)
9754     return SDValue();
9755 
9756   // Make sure the non-chain result is only used by this build vector.
9757   if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
9758     return SDValue();
9759 
9760   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
9761       (Subtarget.hasVLX() && ScalarSize == 64)) {
9762     auto *LN = cast<LoadSDNode>(Ld);
9763     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9764     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
9765     SDValue BCast =
9766         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
9767                                 LN->getMemoryVT(), LN->getMemOperand());
9768     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
9769     return BCast;
9770   }
9771 
9772   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
9773   // double since there is no vbroadcastsd xmm
9774   if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
9775       (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
9776     auto *LN = cast<LoadSDNode>(Ld);
9777     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9778     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
9779     SDValue BCast =
9780         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
9781                                 LN->getMemoryVT(), LN->getMemOperand());
9782     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
9783     return BCast;
9784   }
9785 
9786   if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
9787     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
9788 
9789   // Unsupported broadcast.
9790   return SDValue();
9791 }
9792 
9793 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
9794 /// underlying vector and index.
9795 ///
9796 /// Modifies \p ExtractedFromVec to the real vector and returns the real
9797 /// index.
9798 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
9799                                          SDValue ExtIdx) {
9800   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
9801   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
9802     return Idx;
9803 
9804   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
9805   // lowered this:
9806   //   (extract_vector_elt (v8f32 %1), Constant<6>)
9807   // to:
9808   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
9809   //                           (extract_subvector (v8f32 %0), Constant<4>),
9810   //                           undef)
9811   //                       Constant<0>)
9812   // In this case the vector is the extract_subvector expression and the index
9813   // is 2, as specified by the shuffle.
9814   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
9815   SDValue ShuffleVec = SVOp->getOperand(0);
9816   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
9817   assert(ShuffleVecVT.getVectorElementType() ==
9818          ExtractedFromVec.getSimpleValueType().getVectorElementType());
9819 
9820   int ShuffleIdx = SVOp->getMaskElt(Idx);
9821   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
9822     ExtractedFromVec = ShuffleVec;
9823     return ShuffleIdx;
9824   }
9825   return Idx;
9826 }
9827 
9828 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
9829   MVT VT = Op.getSimpleValueType();
9830 
9831   // Skip if insert_vec_elt is not supported.
9832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9833   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
9834     return SDValue();
9835 
9836   SDLoc DL(Op);
9837   unsigned NumElems = Op.getNumOperands();
9838 
9839   SDValue VecIn1;
9840   SDValue VecIn2;
9841   SmallVector<unsigned, 4> InsertIndices;
9842   SmallVector<int, 8> Mask(NumElems, -1);
9843 
9844   for (unsigned i = 0; i != NumElems; ++i) {
9845     unsigned Opc = Op.getOperand(i).getOpcode();
9846 
9847     if (Opc == ISD::UNDEF)
9848       continue;
9849 
9850     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
9851       // Quit if more than 1 elements need inserting.
9852       if (InsertIndices.size() > 1)
9853         return SDValue();
9854 
9855       InsertIndices.push_back(i);
9856       continue;
9857     }
9858 
9859     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
9860     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
9861 
9862     // Quit if non-constant index.
9863     if (!isa<ConstantSDNode>(ExtIdx))
9864       return SDValue();
9865     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
9866 
9867     // Quit if extracted from vector of different type.
9868     if (ExtractedFromVec.getValueType() != VT)
9869       return SDValue();
9870 
9871     if (!VecIn1.getNode())
9872       VecIn1 = ExtractedFromVec;
9873     else if (VecIn1 != ExtractedFromVec) {
9874       if (!VecIn2.getNode())
9875         VecIn2 = ExtractedFromVec;
9876       else if (VecIn2 != ExtractedFromVec)
9877         // Quit if more than 2 vectors to shuffle
9878         return SDValue();
9879     }
9880 
9881     if (ExtractedFromVec == VecIn1)
9882       Mask[i] = Idx;
9883     else if (ExtractedFromVec == VecIn2)
9884       Mask[i] = Idx + NumElems;
9885   }
9886 
9887   if (!VecIn1.getNode())
9888     return SDValue();
9889 
9890   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9891   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
9892 
9893   for (unsigned Idx : InsertIndices)
9894     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
9895                      DAG.getIntPtrConstant(Idx, DL));
9896 
9897   return NV;
9898 }
9899 
9900 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
9901 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
9902                                      const X86Subtarget &Subtarget) {
9903 
9904   MVT VT = Op.getSimpleValueType();
9905   assert((VT.getVectorElementType() == MVT::i1) &&
9906          "Unexpected type in LowerBUILD_VECTORvXi1!");
9907 
9908   SDLoc dl(Op);
9909   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
9910       ISD::isBuildVectorAllOnes(Op.getNode()))
9911     return Op;
9912 
9913   uint64_t Immediate = 0;
9914   SmallVector<unsigned, 16> NonConstIdx;
9915   bool IsSplat = true;
9916   bool HasConstElts = false;
9917   int SplatIdx = -1;
9918   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
9919     SDValue In = Op.getOperand(idx);
9920     if (In.isUndef())
9921       continue;
9922     if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
9923       Immediate |= (InC->getZExtValue() & 0x1) << idx;
9924       HasConstElts = true;
9925     } else {
9926       NonConstIdx.push_back(idx);
9927     }
9928     if (SplatIdx < 0)
9929       SplatIdx = idx;
9930     else if (In != Op.getOperand(SplatIdx))
9931       IsSplat = false;
9932   }
9933 
9934   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
9935   if (IsSplat) {
9936     // The build_vector allows the scalar element to be larger than the vector
9937     // element type. We need to mask it to use as a condition unless we know
9938     // the upper bits are zero.
9939     // FIXME: Use computeKnownBits instead of checking specific opcode?
9940     SDValue Cond = Op.getOperand(SplatIdx);
9941     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
9942     if (Cond.getOpcode() != ISD::SETCC)
9943       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
9944                          DAG.getConstant(1, dl, MVT::i8));
9945 
9946     // Perform the select in the scalar domain so we can use cmov.
9947     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9948       SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
9949                                      DAG.getAllOnesConstant(dl, MVT::i32),
9950                                      DAG.getConstant(0, dl, MVT::i32));
9951       Select = DAG.getBitcast(MVT::v32i1, Select);
9952       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
9953     } else {
9954       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9955       SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
9956                                      DAG.getAllOnesConstant(dl, ImmVT),
9957                                      DAG.getConstant(0, dl, ImmVT));
9958       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9959       Select = DAG.getBitcast(VecVT, Select);
9960       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
9961                          DAG.getIntPtrConstant(0, dl));
9962     }
9963   }
9964 
9965   // insert elements one by one
9966   SDValue DstVec;
9967   if (HasConstElts) {
9968     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9969       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
9970       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
9971       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
9972       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
9973       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
9974     } else {
9975       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9976       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
9977       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9978       DstVec = DAG.getBitcast(VecVT, Imm);
9979       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
9980                            DAG.getIntPtrConstant(0, dl));
9981     }
9982   } else
9983     DstVec = DAG.getUNDEF(VT);
9984 
9985   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
9986     unsigned InsertIdx = NonConstIdx[i];
9987     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9988                          Op.getOperand(InsertIdx),
9989                          DAG.getIntPtrConstant(InsertIdx, dl));
9990   }
9991   return DstVec;
9992 }
9993 
9994 LLVM_ATTRIBUTE_UNUSED static bool isHorizOp(unsigned Opcode) {
9995   switch (Opcode) {
9996   case X86ISD::PACKSS:
9997   case X86ISD::PACKUS:
9998   case X86ISD::FHADD:
9999   case X86ISD::FHSUB:
10000   case X86ISD::HADD:
10001   case X86ISD::HSUB:
10002     return true;
10003   }
10004   return false;
10005 }
10006 
10007 /// This is a helper function of LowerToHorizontalOp().
10008 /// This function checks that the build_vector \p N in input implements a
10009 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
10010 /// may not match the layout of an x86 256-bit horizontal instruction.
10011 /// In other words, if this returns true, then some extraction/insertion will
10012 /// be required to produce a valid horizontal instruction.
10013 ///
10014 /// Parameter \p Opcode defines the kind of horizontal operation to match.
10015 /// For example, if \p Opcode is equal to ISD::ADD, then this function
10016 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
10017 /// is equal to ISD::SUB, then this function checks if this is a horizontal
10018 /// arithmetic sub.
10019 ///
10020 /// This function only analyzes elements of \p N whose indices are
10021 /// in range [BaseIdx, LastIdx).
10022 ///
10023 /// TODO: This function was originally used to match both real and fake partial
10024 /// horizontal operations, but the index-matching logic is incorrect for that.
10025 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
10026 /// code because it is only used for partial h-op matching now?
10027 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
10028                                   SelectionDAG &DAG,
10029                                   unsigned BaseIdx, unsigned LastIdx,
10030                                   SDValue &V0, SDValue &V1) {
10031   EVT VT = N->getValueType(0);
10032   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
10033   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
10034   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
10035          "Invalid Vector in input!");
10036 
10037   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
10038   bool CanFold = true;
10039   unsigned ExpectedVExtractIdx = BaseIdx;
10040   unsigned NumElts = LastIdx - BaseIdx;
10041   V0 = DAG.getUNDEF(VT);
10042   V1 = DAG.getUNDEF(VT);
10043 
10044   // Check if N implements a horizontal binop.
10045   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
10046     SDValue Op = N->getOperand(i + BaseIdx);
10047 
10048     // Skip UNDEFs.
10049     if (Op->isUndef()) {
10050       // Update the expected vector extract index.
10051       if (i * 2 == NumElts)
10052         ExpectedVExtractIdx = BaseIdx;
10053       ExpectedVExtractIdx += 2;
10054       continue;
10055     }
10056 
10057     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
10058 
10059     if (!CanFold)
10060       break;
10061 
10062     SDValue Op0 = Op.getOperand(0);
10063     SDValue Op1 = Op.getOperand(1);
10064 
10065     // Try to match the following pattern:
10066     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
10067     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10068         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10069         Op0.getOperand(0) == Op1.getOperand(0) &&
10070         isa<ConstantSDNode>(Op0.getOperand(1)) &&
10071         isa<ConstantSDNode>(Op1.getOperand(1)));
10072     if (!CanFold)
10073       break;
10074 
10075     unsigned I0 = Op0.getConstantOperandVal(1);
10076     unsigned I1 = Op1.getConstantOperandVal(1);
10077 
10078     if (i * 2 < NumElts) {
10079       if (V0.isUndef()) {
10080         V0 = Op0.getOperand(0);
10081         if (V0.getValueType() != VT)
10082           return false;
10083       }
10084     } else {
10085       if (V1.isUndef()) {
10086         V1 = Op0.getOperand(0);
10087         if (V1.getValueType() != VT)
10088           return false;
10089       }
10090       if (i * 2 == NumElts)
10091         ExpectedVExtractIdx = BaseIdx;
10092     }
10093 
10094     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
10095     if (I0 == ExpectedVExtractIdx)
10096       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
10097     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
10098       // Try to match the following dag sequence:
10099       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
10100       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
10101     } else
10102       CanFold = false;
10103 
10104     ExpectedVExtractIdx += 2;
10105   }
10106 
10107   return CanFold;
10108 }
10109 
10110 /// Emit a sequence of two 128-bit horizontal add/sub followed by
10111 /// a concat_vector.
10112 ///
10113 /// This is a helper function of LowerToHorizontalOp().
10114 /// This function expects two 256-bit vectors called V0 and V1.
10115 /// At first, each vector is split into two separate 128-bit vectors.
10116 /// Then, the resulting 128-bit vectors are used to implement two
10117 /// horizontal binary operations.
10118 ///
10119 /// The kind of horizontal binary operation is defined by \p X86Opcode.
10120 ///
10121 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
10122 /// the two new horizontal binop.
10123 /// When Mode is set, the first horizontal binop dag node would take as input
10124 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
10125 /// horizontal binop dag node would take as input the lower 128-bit of V1
10126 /// and the upper 128-bit of V1.
10127 ///   Example:
10128 ///     HADD V0_LO, V0_HI
10129 ///     HADD V1_LO, V1_HI
10130 ///
10131 /// Otherwise, the first horizontal binop dag node takes as input the lower
10132 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
10133 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
10134 ///   Example:
10135 ///     HADD V0_LO, V1_LO
10136 ///     HADD V0_HI, V1_HI
10137 ///
10138 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
10139 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
10140 /// the upper 128-bits of the result.
10141 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
10142                                      const SDLoc &DL, SelectionDAG &DAG,
10143                                      unsigned X86Opcode, bool Mode,
10144                                      bool isUndefLO, bool isUndefHI) {
10145   MVT VT = V0.getSimpleValueType();
10146   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
10147          "Invalid nodes in input!");
10148 
10149   unsigned NumElts = VT.getVectorNumElements();
10150   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
10151   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
10152   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
10153   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
10154   MVT NewVT = V0_LO.getSimpleValueType();
10155 
10156   SDValue LO = DAG.getUNDEF(NewVT);
10157   SDValue HI = DAG.getUNDEF(NewVT);
10158 
10159   if (Mode) {
10160     // Don't emit a horizontal binop if the result is expected to be UNDEF.
10161     if (!isUndefLO && !V0->isUndef())
10162       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
10163     if (!isUndefHI && !V1->isUndef())
10164       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
10165   } else {
10166     // Don't emit a horizontal binop if the result is expected to be UNDEF.
10167     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
10168       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
10169 
10170     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
10171       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
10172   }
10173 
10174   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
10175 }
10176 
10177 /// Returns true iff \p BV builds a vector with the result equivalent to
10178 /// the result of ADDSUB/SUBADD operation.
10179 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
10180 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
10181 /// \p Opnd0 and \p Opnd1.
10182 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
10183                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
10184                              SDValue &Opnd0, SDValue &Opnd1,
10185                              unsigned &NumExtracts,
10186                              bool &IsSubAdd) {
10187 
10188   MVT VT = BV->getSimpleValueType(0);
10189   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
10190     return false;
10191 
10192   unsigned NumElts = VT.getVectorNumElements();
10193   SDValue InVec0 = DAG.getUNDEF(VT);
10194   SDValue InVec1 = DAG.getUNDEF(VT);
10195 
10196   NumExtracts = 0;
10197 
10198   // Odd-numbered elements in the input build vector are obtained from
10199   // adding/subtracting two integer/float elements.
10200   // Even-numbered elements in the input build vector are obtained from
10201   // subtracting/adding two integer/float elements.
10202   unsigned Opc[2] = {0, 0};
10203   for (unsigned i = 0, e = NumElts; i != e; ++i) {
10204     SDValue Op = BV->getOperand(i);
10205 
10206     // Skip 'undef' values.
10207     unsigned Opcode = Op.getOpcode();
10208     if (Opcode == ISD::UNDEF)
10209       continue;
10210 
10211     // Early exit if we found an unexpected opcode.
10212     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
10213       return false;
10214 
10215     SDValue Op0 = Op.getOperand(0);
10216     SDValue Op1 = Op.getOperand(1);
10217 
10218     // Try to match the following pattern:
10219     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
10220     // Early exit if we cannot match that sequence.
10221     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10222         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10223         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
10224         Op0.getOperand(1) != Op1.getOperand(1))
10225       return false;
10226 
10227     unsigned I0 = Op0.getConstantOperandVal(1);
10228     if (I0 != i)
10229       return false;
10230 
10231     // We found a valid add/sub node, make sure its the same opcode as previous
10232     // elements for this parity.
10233     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
10234       return false;
10235     Opc[i % 2] = Opcode;
10236 
10237     // Update InVec0 and InVec1.
10238     if (InVec0.isUndef()) {
10239       InVec0 = Op0.getOperand(0);
10240       if (InVec0.getSimpleValueType() != VT)
10241         return false;
10242     }
10243     if (InVec1.isUndef()) {
10244       InVec1 = Op1.getOperand(0);
10245       if (InVec1.getSimpleValueType() != VT)
10246         return false;
10247     }
10248 
10249     // Make sure that operands in input to each add/sub node always
10250     // come from a same pair of vectors.
10251     if (InVec0 != Op0.getOperand(0)) {
10252       if (Opcode == ISD::FSUB)
10253         return false;
10254 
10255       // FADD is commutable. Try to commute the operands
10256       // and then test again.
10257       std::swap(Op0, Op1);
10258       if (InVec0 != Op0.getOperand(0))
10259         return false;
10260     }
10261 
10262     if (InVec1 != Op1.getOperand(0))
10263       return false;
10264 
10265     // Increment the number of extractions done.
10266     ++NumExtracts;
10267   }
10268 
10269   // Ensure we have found an opcode for both parities and that they are
10270   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
10271   // inputs are undef.
10272   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
10273       InVec0.isUndef() || InVec1.isUndef())
10274     return false;
10275 
10276   IsSubAdd = Opc[0] == ISD::FADD;
10277 
10278   Opnd0 = InVec0;
10279   Opnd1 = InVec1;
10280   return true;
10281 }
10282 
10283 /// Returns true if is possible to fold MUL and an idiom that has already been
10284 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
10285 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
10286 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
10287 ///
10288 /// Prior to calling this function it should be known that there is some
10289 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
10290 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
10291 /// before replacement of such SDNode with ADDSUB operation. Thus the number
10292 /// of \p Opnd0 uses is expected to be equal to 2.
10293 /// For example, this function may be called for the following IR:
10294 ///    %AB = fmul fast <2 x double> %A, %B
10295 ///    %Sub = fsub fast <2 x double> %AB, %C
10296 ///    %Add = fadd fast <2 x double> %AB, %C
10297 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
10298 ///                            <2 x i32> <i32 0, i32 3>
10299 /// There is a def for %Addsub here, which potentially can be replaced by
10300 /// X86ISD::ADDSUB operation:
10301 ///    %Addsub = X86ISD::ADDSUB %AB, %C
10302 /// and such ADDSUB can further be replaced with FMADDSUB:
10303 ///    %Addsub = FMADDSUB %A, %B, %C.
10304 ///
10305 /// The main reason why this method is called before the replacement of the
10306 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
10307 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
10308 /// FMADDSUB is.
10309 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
10310                                  SelectionDAG &DAG,
10311                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
10312                                  unsigned ExpectedUses) {
10313   if (Opnd0.getOpcode() != ISD::FMUL ||
10314       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
10315     return false;
10316 
10317   // FIXME: These checks must match the similar ones in
10318   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
10319   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
10320   // or MUL + ADDSUB to FMADDSUB.
10321   const TargetOptions &Options = DAG.getTarget().Options;
10322   bool AllowFusion =
10323       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
10324   if (!AllowFusion)
10325     return false;
10326 
10327   Opnd2 = Opnd1;
10328   Opnd1 = Opnd0.getOperand(1);
10329   Opnd0 = Opnd0.getOperand(0);
10330 
10331   return true;
10332 }
10333 
10334 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
10335 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
10336 /// X86ISD::FMSUBADD node.
10337 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
10338                                        const X86Subtarget &Subtarget,
10339                                        SelectionDAG &DAG) {
10340   SDValue Opnd0, Opnd1;
10341   unsigned NumExtracts;
10342   bool IsSubAdd;
10343   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
10344                         IsSubAdd))
10345     return SDValue();
10346 
10347   MVT VT = BV->getSimpleValueType(0);
10348   SDLoc DL(BV);
10349 
10350   // Try to generate X86ISD::FMADDSUB node here.
10351   SDValue Opnd2;
10352   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
10353     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
10354     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
10355   }
10356 
10357   // We only support ADDSUB.
10358   if (IsSubAdd)
10359     return SDValue();
10360 
10361   // There are no known X86 targets with 512-bit ADDSUB instructions!
10362   // Convert to blend(fsub,fadd).
10363   if (VT.is512BitVector()) {
10364     SmallVector<int> Mask;
10365     for (int I = 0, E = VT.getVectorNumElements(); I != E; I += 2) {
10366         Mask.push_back(I);
10367         Mask.push_back(I + E + 1);
10368     }
10369     SDValue Sub = DAG.getNode(ISD::FSUB, DL, VT, Opnd0, Opnd1);
10370     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, Opnd0, Opnd1);
10371     return DAG.getVectorShuffle(VT, DL, Sub, Add, Mask);
10372   }
10373 
10374   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
10375 }
10376 
10377 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
10378                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
10379   // Initialize outputs to known values.
10380   MVT VT = BV->getSimpleValueType(0);
10381   HOpcode = ISD::DELETED_NODE;
10382   V0 = DAG.getUNDEF(VT);
10383   V1 = DAG.getUNDEF(VT);
10384 
10385   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
10386   // half of the result is calculated independently from the 128-bit halves of
10387   // the inputs, so that makes the index-checking logic below more complicated.
10388   unsigned NumElts = VT.getVectorNumElements();
10389   unsigned GenericOpcode = ISD::DELETED_NODE;
10390   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
10391   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
10392   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
10393   for (unsigned i = 0; i != Num128BitChunks; ++i) {
10394     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
10395       // Ignore undef elements.
10396       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
10397       if (Op.isUndef())
10398         continue;
10399 
10400       // If there's an opcode mismatch, we're done.
10401       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
10402         return false;
10403 
10404       // Initialize horizontal opcode.
10405       if (HOpcode == ISD::DELETED_NODE) {
10406         GenericOpcode = Op.getOpcode();
10407         switch (GenericOpcode) {
10408         case ISD::ADD: HOpcode = X86ISD::HADD; break;
10409         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
10410         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
10411         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
10412         default: return false;
10413         }
10414       }
10415 
10416       SDValue Op0 = Op.getOperand(0);
10417       SDValue Op1 = Op.getOperand(1);
10418       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10419           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10420           Op0.getOperand(0) != Op1.getOperand(0) ||
10421           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
10422           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
10423         return false;
10424 
10425       // The source vector is chosen based on which 64-bit half of the
10426       // destination vector is being calculated.
10427       if (j < NumEltsIn64Bits) {
10428         if (V0.isUndef())
10429           V0 = Op0.getOperand(0);
10430       } else {
10431         if (V1.isUndef())
10432           V1 = Op0.getOperand(0);
10433       }
10434 
10435       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
10436       if (SourceVec != Op0.getOperand(0))
10437         return false;
10438 
10439       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
10440       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
10441       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
10442       unsigned ExpectedIndex = i * NumEltsIn128Bits +
10443                                (j % NumEltsIn64Bits) * 2;
10444       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
10445         continue;
10446 
10447       // If this is not a commutative op, this does not match.
10448       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
10449         return false;
10450 
10451       // Addition is commutative, so try swapping the extract indexes.
10452       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
10453       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
10454         continue;
10455 
10456       // Extract indexes do not match horizontal requirement.
10457       return false;
10458     }
10459   }
10460   // We matched. Opcode and operands are returned by reference as arguments.
10461   return true;
10462 }
10463 
10464 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
10465                                     SelectionDAG &DAG, unsigned HOpcode,
10466                                     SDValue V0, SDValue V1) {
10467   // If either input vector is not the same size as the build vector,
10468   // extract/insert the low bits to the correct size.
10469   // This is free (examples: zmm --> xmm, xmm --> ymm).
10470   MVT VT = BV->getSimpleValueType(0);
10471   unsigned Width = VT.getSizeInBits();
10472   if (V0.getValueSizeInBits() > Width)
10473     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
10474   else if (V0.getValueSizeInBits() < Width)
10475     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
10476 
10477   if (V1.getValueSizeInBits() > Width)
10478     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
10479   else if (V1.getValueSizeInBits() < Width)
10480     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
10481 
10482   unsigned NumElts = VT.getVectorNumElements();
10483   APInt DemandedElts = APInt::getAllOnes(NumElts);
10484   for (unsigned i = 0; i != NumElts; ++i)
10485     if (BV->getOperand(i).isUndef())
10486       DemandedElts.clearBit(i);
10487 
10488   // If we don't need the upper xmm, then perform as a xmm hop.
10489   unsigned HalfNumElts = NumElts / 2;
10490   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
10491     MVT HalfVT = VT.getHalfNumVectorElementsVT();
10492     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
10493     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
10494     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
10495     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
10496   }
10497 
10498   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
10499 }
10500 
10501 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
10502 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
10503                                    const X86Subtarget &Subtarget,
10504                                    SelectionDAG &DAG) {
10505   // We need at least 2 non-undef elements to make this worthwhile by default.
10506   unsigned NumNonUndefs =
10507       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
10508   if (NumNonUndefs < 2)
10509     return SDValue();
10510 
10511   // There are 4 sets of horizontal math operations distinguished by type:
10512   // int/FP at 128-bit/256-bit. Each type was introduced with a different
10513   // subtarget feature. Try to match those "native" patterns first.
10514   MVT VT = BV->getSimpleValueType(0);
10515   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
10516       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
10517       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
10518       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
10519     unsigned HOpcode;
10520     SDValue V0, V1;
10521     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
10522       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
10523   }
10524 
10525   // Try harder to match 256-bit ops by using extract/concat.
10526   if (!Subtarget.hasAVX() || !VT.is256BitVector())
10527     return SDValue();
10528 
10529   // Count the number of UNDEF operands in the build_vector in input.
10530   unsigned NumElts = VT.getVectorNumElements();
10531   unsigned Half = NumElts / 2;
10532   unsigned NumUndefsLO = 0;
10533   unsigned NumUndefsHI = 0;
10534   for (unsigned i = 0, e = Half; i != e; ++i)
10535     if (BV->getOperand(i)->isUndef())
10536       NumUndefsLO++;
10537 
10538   for (unsigned i = Half, e = NumElts; i != e; ++i)
10539     if (BV->getOperand(i)->isUndef())
10540       NumUndefsHI++;
10541 
10542   SDLoc DL(BV);
10543   SDValue InVec0, InVec1;
10544   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
10545     SDValue InVec2, InVec3;
10546     unsigned X86Opcode;
10547     bool CanFold = true;
10548 
10549     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
10550         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
10551                               InVec3) &&
10552         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
10553         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
10554       X86Opcode = X86ISD::HADD;
10555     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
10556                                    InVec1) &&
10557              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
10558                                    InVec3) &&
10559              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
10560              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
10561       X86Opcode = X86ISD::HSUB;
10562     else
10563       CanFold = false;
10564 
10565     if (CanFold) {
10566       // Do not try to expand this build_vector into a pair of horizontal
10567       // add/sub if we can emit a pair of scalar add/sub.
10568       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
10569         return SDValue();
10570 
10571       // Convert this build_vector into a pair of horizontal binops followed by
10572       // a concat vector. We must adjust the outputs from the partial horizontal
10573       // matching calls above to account for undefined vector halves.
10574       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
10575       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
10576       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
10577       bool isUndefLO = NumUndefsLO == Half;
10578       bool isUndefHI = NumUndefsHI == Half;
10579       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
10580                                    isUndefHI);
10581     }
10582   }
10583 
10584   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
10585       VT == MVT::v16i16) {
10586     unsigned X86Opcode;
10587     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
10588       X86Opcode = X86ISD::HADD;
10589     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
10590                                    InVec1))
10591       X86Opcode = X86ISD::HSUB;
10592     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
10593                                    InVec1))
10594       X86Opcode = X86ISD::FHADD;
10595     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
10596                                    InVec1))
10597       X86Opcode = X86ISD::FHSUB;
10598     else
10599       return SDValue();
10600 
10601     // Don't try to expand this build_vector into a pair of horizontal add/sub
10602     // if we can simply emit a pair of scalar add/sub.
10603     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
10604       return SDValue();
10605 
10606     // Convert this build_vector into two horizontal add/sub followed by
10607     // a concat vector.
10608     bool isUndefLO = NumUndefsLO == Half;
10609     bool isUndefHI = NumUndefsHI == Half;
10610     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
10611                                  isUndefLO, isUndefHI);
10612   }
10613 
10614   return SDValue();
10615 }
10616 
10617 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
10618                           SelectionDAG &DAG);
10619 
10620 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
10621 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
10622 /// just apply the bit to the vectors.
10623 /// NOTE: Its not in our interest to start make a general purpose vectorizer
10624 /// from this, but enough scalar bit operations are created from the later
10625 /// legalization + scalarization stages to need basic support.
10626 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
10627                                        const X86Subtarget &Subtarget,
10628                                        SelectionDAG &DAG) {
10629   SDLoc DL(Op);
10630   MVT VT = Op->getSimpleValueType(0);
10631   unsigned NumElems = VT.getVectorNumElements();
10632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10633 
10634   // Check that all elements have the same opcode.
10635   // TODO: Should we allow UNDEFS and if so how many?
10636   unsigned Opcode = Op->getOperand(0).getOpcode();
10637   for (unsigned i = 1; i < NumElems; ++i)
10638     if (Opcode != Op->getOperand(i).getOpcode())
10639       return SDValue();
10640 
10641   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
10642   bool IsShift = false;
10643   switch (Opcode) {
10644   default:
10645     return SDValue();
10646   case ISD::SHL:
10647   case ISD::SRL:
10648   case ISD::SRA:
10649     IsShift = true;
10650     break;
10651   case ISD::AND:
10652   case ISD::XOR:
10653   case ISD::OR:
10654     // Don't do this if the buildvector is a splat - we'd replace one
10655     // constant with an entire vector.
10656     if (Op->getSplatValue())
10657       return SDValue();
10658     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
10659       return SDValue();
10660     break;
10661   }
10662 
10663   SmallVector<SDValue, 4> LHSElts, RHSElts;
10664   for (SDValue Elt : Op->ops()) {
10665     SDValue LHS = Elt.getOperand(0);
10666     SDValue RHS = Elt.getOperand(1);
10667 
10668     // We expect the canonicalized RHS operand to be the constant.
10669     if (!isa<ConstantSDNode>(RHS))
10670       return SDValue();
10671 
10672     // Extend shift amounts.
10673     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
10674       if (!IsShift)
10675         return SDValue();
10676       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
10677     }
10678 
10679     LHSElts.push_back(LHS);
10680     RHSElts.push_back(RHS);
10681   }
10682 
10683   // Limit to shifts by uniform immediates.
10684   // TODO: Only accept vXi8/vXi64 special cases?
10685   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
10686   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
10687     return SDValue();
10688 
10689   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
10690   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
10691   SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
10692 
10693   if (!IsShift)
10694     return Res;
10695 
10696   // Immediately lower the shift to ensure the constant build vector doesn't
10697   // get converted to a constant pool before the shift is lowered.
10698   return LowerShift(Res, Subtarget, DAG);
10699 }
10700 
10701 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
10702 /// functionality to do this, so it's all zeros, all ones, or some derivation
10703 /// that is cheap to calculate.
10704 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
10705                                          const X86Subtarget &Subtarget) {
10706   SDLoc DL(Op);
10707   MVT VT = Op.getSimpleValueType();
10708 
10709   // Vectors containing all zeros can be matched by pxor and xorps.
10710   if (ISD::isBuildVectorAllZeros(Op.getNode()))
10711     return Op;
10712 
10713   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
10714   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
10715   // vpcmpeqd on 256-bit vectors.
10716   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
10717     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
10718       return Op;
10719 
10720     return getOnesVector(VT, DAG, DL);
10721   }
10722 
10723   return SDValue();
10724 }
10725 
10726 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
10727 /// from a vector of source values and a vector of extraction indices.
10728 /// The vectors might be manipulated to match the type of the permute op.
10729 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
10730                                      SDLoc &DL, SelectionDAG &DAG,
10731                                      const X86Subtarget &Subtarget) {
10732   MVT ShuffleVT = VT;
10733   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
10734   unsigned NumElts = VT.getVectorNumElements();
10735   unsigned SizeInBits = VT.getSizeInBits();
10736 
10737   // Adjust IndicesVec to match VT size.
10738   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
10739          "Illegal variable permute mask size");
10740   if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
10741     // Narrow/widen the indices vector to the correct size.
10742     if (IndicesVec.getValueSizeInBits() > SizeInBits)
10743       IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
10744                                     NumElts * VT.getScalarSizeInBits());
10745     else if (IndicesVec.getValueSizeInBits() < SizeInBits)
10746       IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
10747                                   SDLoc(IndicesVec), SizeInBits);
10748     // Zero-extend the index elements within the vector.
10749     if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
10750       IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
10751                                IndicesVT, IndicesVec);
10752   }
10753   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
10754 
10755   // Handle SrcVec that don't match VT type.
10756   if (SrcVec.getValueSizeInBits() != SizeInBits) {
10757     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
10758       // Handle larger SrcVec by treating it as a larger permute.
10759       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
10760       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
10761       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
10762       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
10763                                   Subtarget, DAG, SDLoc(IndicesVec));
10764       SDValue NewSrcVec =
10765           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10766       if (NewSrcVec)
10767         return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
10768       return SDValue();
10769     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
10770       // Widen smaller SrcVec to match VT.
10771       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
10772     } else
10773       return SDValue();
10774   }
10775 
10776   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
10777     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
10778     EVT SrcVT = Idx.getValueType();
10779     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
10780     uint64_t IndexScale = 0;
10781     uint64_t IndexOffset = 0;
10782 
10783     // If we're scaling a smaller permute op, then we need to repeat the
10784     // indices, scaling and offsetting them as well.
10785     // e.g. v4i32 -> v16i8 (Scale = 4)
10786     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
10787     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
10788     for (uint64_t i = 0; i != Scale; ++i) {
10789       IndexScale |= Scale << (i * NumDstBits);
10790       IndexOffset |= i << (i * NumDstBits);
10791     }
10792 
10793     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
10794                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
10795     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
10796                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
10797     return Idx;
10798   };
10799 
10800   unsigned Opcode = 0;
10801   switch (VT.SimpleTy) {
10802   default:
10803     break;
10804   case MVT::v16i8:
10805     if (Subtarget.hasSSSE3())
10806       Opcode = X86ISD::PSHUFB;
10807     break;
10808   case MVT::v8i16:
10809     if (Subtarget.hasVLX() && Subtarget.hasBWI())
10810       Opcode = X86ISD::VPERMV;
10811     else if (Subtarget.hasSSSE3()) {
10812       Opcode = X86ISD::PSHUFB;
10813       ShuffleVT = MVT::v16i8;
10814     }
10815     break;
10816   case MVT::v4f32:
10817   case MVT::v4i32:
10818     if (Subtarget.hasAVX()) {
10819       Opcode = X86ISD::VPERMILPV;
10820       ShuffleVT = MVT::v4f32;
10821     } else if (Subtarget.hasSSSE3()) {
10822       Opcode = X86ISD::PSHUFB;
10823       ShuffleVT = MVT::v16i8;
10824     }
10825     break;
10826   case MVT::v2f64:
10827   case MVT::v2i64:
10828     if (Subtarget.hasAVX()) {
10829       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
10830       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10831       Opcode = X86ISD::VPERMILPV;
10832       ShuffleVT = MVT::v2f64;
10833     } else if (Subtarget.hasSSE41()) {
10834       // SSE41 can compare v2i64 - select between indices 0 and 1.
10835       return DAG.getSelectCC(
10836           DL, IndicesVec,
10837           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
10838           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
10839           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
10840           ISD::CondCode::SETEQ);
10841     }
10842     break;
10843   case MVT::v32i8:
10844     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
10845       Opcode = X86ISD::VPERMV;
10846     else if (Subtarget.hasXOP()) {
10847       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
10848       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
10849       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
10850       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
10851       return DAG.getNode(
10852           ISD::CONCAT_VECTORS, DL, VT,
10853           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
10854           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
10855     } else if (Subtarget.hasAVX()) {
10856       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
10857       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
10858       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
10859       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
10860       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
10861                               ArrayRef<SDValue> Ops) {
10862         // Permute Lo and Hi and then select based on index range.
10863         // This works as SHUFB uses bits[3:0] to permute elements and we don't
10864         // care about the bit[7] as its just an index vector.
10865         SDValue Idx = Ops[2];
10866         EVT VT = Idx.getValueType();
10867         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
10868                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
10869                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
10870                                ISD::CondCode::SETGT);
10871       };
10872       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
10873       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
10874                               PSHUFBBuilder);
10875     }
10876     break;
10877   case MVT::v16i16:
10878     if (Subtarget.hasVLX() && Subtarget.hasBWI())
10879       Opcode = X86ISD::VPERMV;
10880     else if (Subtarget.hasAVX()) {
10881       // Scale to v32i8 and perform as v32i8.
10882       IndicesVec = ScaleIndices(IndicesVec, 2);
10883       return DAG.getBitcast(
10884           VT, createVariablePermute(
10885                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
10886                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
10887     }
10888     break;
10889   case MVT::v8f32:
10890   case MVT::v8i32:
10891     if (Subtarget.hasAVX2())
10892       Opcode = X86ISD::VPERMV;
10893     else if (Subtarget.hasAVX()) {
10894       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
10895       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10896                                           {0, 1, 2, 3, 0, 1, 2, 3});
10897       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10898                                           {4, 5, 6, 7, 4, 5, 6, 7});
10899       if (Subtarget.hasXOP())
10900         return DAG.getBitcast(
10901             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
10902                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10903       // Permute Lo and Hi and then select based on index range.
10904       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
10905       SDValue Res = DAG.getSelectCC(
10906           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
10907           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
10908           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
10909           ISD::CondCode::SETGT);
10910       return DAG.getBitcast(VT, Res);
10911     }
10912     break;
10913   case MVT::v4i64:
10914   case MVT::v4f64:
10915     if (Subtarget.hasAVX512()) {
10916       if (!Subtarget.hasVLX()) {
10917         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
10918         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
10919                                 SDLoc(SrcVec));
10920         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
10921                                     DAG, SDLoc(IndicesVec));
10922         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
10923                                             DAG, Subtarget);
10924         return extract256BitVector(Res, 0, DAG, DL);
10925       }
10926       Opcode = X86ISD::VPERMV;
10927     } else if (Subtarget.hasAVX()) {
10928       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
10929       SDValue LoLo =
10930           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
10931       SDValue HiHi =
10932           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
10933       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
10934       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10935       if (Subtarget.hasXOP())
10936         return DAG.getBitcast(
10937             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
10938                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10939       // Permute Lo and Hi and then select based on index range.
10940       // This works as VPERMILPD only uses index bit[1] to permute elements.
10941       SDValue Res = DAG.getSelectCC(
10942           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
10943           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
10944           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
10945           ISD::CondCode::SETGT);
10946       return DAG.getBitcast(VT, Res);
10947     }
10948     break;
10949   case MVT::v64i8:
10950     if (Subtarget.hasVBMI())
10951       Opcode = X86ISD::VPERMV;
10952     break;
10953   case MVT::v32i16:
10954     if (Subtarget.hasBWI())
10955       Opcode = X86ISD::VPERMV;
10956     break;
10957   case MVT::v16f32:
10958   case MVT::v16i32:
10959   case MVT::v8f64:
10960   case MVT::v8i64:
10961     if (Subtarget.hasAVX512())
10962       Opcode = X86ISD::VPERMV;
10963     break;
10964   }
10965   if (!Opcode)
10966     return SDValue();
10967 
10968   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
10969          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
10970          "Illegal variable permute shuffle type");
10971 
10972   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
10973   if (Scale > 1)
10974     IndicesVec = ScaleIndices(IndicesVec, Scale);
10975 
10976   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
10977   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
10978 
10979   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
10980   SDValue Res = Opcode == X86ISD::VPERMV
10981                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
10982                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
10983   return DAG.getBitcast(VT, Res);
10984 }
10985 
10986 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
10987 // reasoned to be a permutation of a vector by indices in a non-constant vector.
10988 // (build_vector (extract_elt V, (extract_elt I, 0)),
10989 //               (extract_elt V, (extract_elt I, 1)),
10990 //                    ...
10991 // ->
10992 // (vpermv I, V)
10993 //
10994 // TODO: Handle undefs
10995 // TODO: Utilize pshufb and zero mask blending to support more efficient
10996 // construction of vectors with constant-0 elements.
10997 static SDValue
10998 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
10999                                    const X86Subtarget &Subtarget) {
11000   SDValue SrcVec, IndicesVec;
11001   // Check for a match of the permute source vector and permute index elements.
11002   // This is done by checking that the i-th build_vector operand is of the form:
11003   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
11004   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
11005     SDValue Op = V.getOperand(Idx);
11006     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11007       return SDValue();
11008 
11009     // If this is the first extract encountered in V, set the source vector,
11010     // otherwise verify the extract is from the previously defined source
11011     // vector.
11012     if (!SrcVec)
11013       SrcVec = Op.getOperand(0);
11014     else if (SrcVec != Op.getOperand(0))
11015       return SDValue();
11016     SDValue ExtractedIndex = Op->getOperand(1);
11017     // Peek through extends.
11018     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
11019         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
11020       ExtractedIndex = ExtractedIndex.getOperand(0);
11021     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11022       return SDValue();
11023 
11024     // If this is the first extract from the index vector candidate, set the
11025     // indices vector, otherwise verify the extract is from the previously
11026     // defined indices vector.
11027     if (!IndicesVec)
11028       IndicesVec = ExtractedIndex.getOperand(0);
11029     else if (IndicesVec != ExtractedIndex.getOperand(0))
11030       return SDValue();
11031 
11032     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
11033     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
11034       return SDValue();
11035   }
11036 
11037   SDLoc DL(V);
11038   MVT VT = V.getSimpleValueType();
11039   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
11040 }
11041 
11042 SDValue
11043 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
11044   SDLoc dl(Op);
11045 
11046   MVT VT = Op.getSimpleValueType();
11047   MVT EltVT = VT.getVectorElementType();
11048   unsigned NumElems = Op.getNumOperands();
11049 
11050   // Generate vectors for predicate vectors.
11051   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
11052     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
11053 
11054   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
11055     return VectorConstant;
11056 
11057   unsigned EVTBits = EltVT.getSizeInBits();
11058   APInt UndefMask = APInt::getZero(NumElems);
11059   APInt ZeroMask = APInt::getZero(NumElems);
11060   APInt NonZeroMask = APInt::getZero(NumElems);
11061   bool IsAllConstants = true;
11062   SmallSet<SDValue, 8> Values;
11063   unsigned NumConstants = NumElems;
11064   for (unsigned i = 0; i < NumElems; ++i) {
11065     SDValue Elt = Op.getOperand(i);
11066     if (Elt.isUndef()) {
11067       UndefMask.setBit(i);
11068       continue;
11069     }
11070     Values.insert(Elt);
11071     if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
11072       IsAllConstants = false;
11073       NumConstants--;
11074     }
11075     if (X86::isZeroNode(Elt)) {
11076       ZeroMask.setBit(i);
11077     } else {
11078       NonZeroMask.setBit(i);
11079     }
11080   }
11081 
11082   // All undef vector. Return an UNDEF. All zero vectors were handled above.
11083   if (NonZeroMask == 0) {
11084     assert(UndefMask.isAllOnes() && "Fully undef mask expected");
11085     return DAG.getUNDEF(VT);
11086   }
11087 
11088   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
11089 
11090   // If the upper elts of a ymm/zmm are undef/zero then we might be better off
11091   // lowering to a smaller build vector and padding with undef/zero.
11092   if ((VT.is256BitVector() || VT.is512BitVector()) &&
11093       !isFoldableUseOfShuffle(BV)) {
11094     unsigned UpperElems = NumElems / 2;
11095     APInt UndefOrZeroMask = UndefMask | ZeroMask;
11096     unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countLeadingOnes();
11097     if (NumUpperUndefsOrZeros >= UpperElems) {
11098       if (VT.is512BitVector() &&
11099           NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
11100         UpperElems = NumElems - (NumElems / 4);
11101       bool UndefUpper = UndefMask.countLeadingOnes() >= UpperElems;
11102       MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
11103       SDValue NewBV =
11104           DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
11105       return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
11106     }
11107   }
11108 
11109   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
11110     return AddSub;
11111   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
11112     return HorizontalOp;
11113   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
11114     return Broadcast;
11115   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
11116     return BitOp;
11117 
11118   unsigned NumZero = ZeroMask.countPopulation();
11119   unsigned NumNonZero = NonZeroMask.countPopulation();
11120 
11121   // If we are inserting one variable into a vector of non-zero constants, try
11122   // to avoid loading each constant element as a scalar. Load the constants as a
11123   // vector and then insert the variable scalar element. If insertion is not
11124   // supported, fall back to a shuffle to get the scalar blended with the
11125   // constants. Insertion into a zero vector is handled as a special-case
11126   // somewhere below here.
11127   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
11128       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
11129        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
11130     // Create an all-constant vector. The variable element in the old
11131     // build vector is replaced by undef in the constant vector. Save the
11132     // variable scalar element and its index for use in the insertelement.
11133     LLVMContext &Context = *DAG.getContext();
11134     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
11135     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
11136     SDValue VarElt;
11137     SDValue InsIndex;
11138     for (unsigned i = 0; i != NumElems; ++i) {
11139       SDValue Elt = Op.getOperand(i);
11140       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
11141         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
11142       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
11143         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
11144       else if (!Elt.isUndef()) {
11145         assert(!VarElt.getNode() && !InsIndex.getNode() &&
11146                "Expected one variable element in this vector");
11147         VarElt = Elt;
11148         InsIndex = DAG.getVectorIdxConstant(i, dl);
11149       }
11150     }
11151     Constant *CV = ConstantVector::get(ConstVecOps);
11152     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
11153 
11154     // The constants we just created may not be legal (eg, floating point). We
11155     // must lower the vector right here because we can not guarantee that we'll
11156     // legalize it before loading it. This is also why we could not just create
11157     // a new build vector here. If the build vector contains illegal constants,
11158     // it could get split back up into a series of insert elements.
11159     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
11160     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
11161     MachineFunction &MF = DAG.getMachineFunction();
11162     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
11163     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
11164     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
11165     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
11166     if (InsertC < NumEltsInLow128Bits)
11167       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
11168 
11169     // There's no good way to insert into the high elements of a >128-bit
11170     // vector, so use shuffles to avoid an extract/insert sequence.
11171     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
11172     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
11173     SmallVector<int, 8> ShuffleMask;
11174     unsigned NumElts = VT.getVectorNumElements();
11175     for (unsigned i = 0; i != NumElts; ++i)
11176       ShuffleMask.push_back(i == InsertC ? NumElts : i);
11177     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
11178     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
11179   }
11180 
11181   // Special case for single non-zero, non-undef, element.
11182   if (NumNonZero == 1) {
11183     unsigned Idx = NonZeroMask.countTrailingZeros();
11184     SDValue Item = Op.getOperand(Idx);
11185 
11186     // If we have a constant or non-constant insertion into the low element of
11187     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
11188     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
11189     // depending on what the source datatype is.
11190     if (Idx == 0) {
11191       if (NumZero == 0)
11192         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
11193 
11194       if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
11195           EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
11196           (EltVT == MVT::i16 && Subtarget.hasFP16())) {
11197         assert((VT.is128BitVector() || VT.is256BitVector() ||
11198                 VT.is512BitVector()) &&
11199                "Expected an SSE value type!");
11200         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
11201         // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
11202         // zero vector.
11203         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
11204       }
11205 
11206       // We can't directly insert an i8 or i16 into a vector, so zero extend
11207       // it to i32 first.
11208       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
11209         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
11210         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
11211         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
11212         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
11213         return DAG.getBitcast(VT, Item);
11214       }
11215     }
11216 
11217     // Is it a vector logical left shift?
11218     if (NumElems == 2 && Idx == 1 &&
11219         X86::isZeroNode(Op.getOperand(0)) &&
11220         !X86::isZeroNode(Op.getOperand(1))) {
11221       unsigned NumBits = VT.getSizeInBits();
11222       return getVShift(true, VT,
11223                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11224                                    VT, Op.getOperand(1)),
11225                        NumBits/2, DAG, *this, dl);
11226     }
11227 
11228     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
11229       return SDValue();
11230 
11231     // Otherwise, if this is a vector with i32 or f32 elements, and the element
11232     // is a non-constant being inserted into an element other than the low one,
11233     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
11234     // movd/movss) to move this into the low element, then shuffle it into
11235     // place.
11236     if (EVTBits == 32) {
11237       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
11238       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
11239     }
11240   }
11241 
11242   // Splat is obviously ok. Let legalizer expand it to a shuffle.
11243   if (Values.size() == 1) {
11244     if (EVTBits == 32) {
11245       // Instead of a shuffle like this:
11246       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
11247       // Check if it's possible to issue this instead.
11248       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
11249       unsigned Idx = NonZeroMask.countTrailingZeros();
11250       SDValue Item = Op.getOperand(Idx);
11251       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
11252         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
11253     }
11254     return SDValue();
11255   }
11256 
11257   // A vector full of immediates; various special cases are already
11258   // handled, so this is best done with a single constant-pool load.
11259   if (IsAllConstants)
11260     return SDValue();
11261 
11262   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
11263       return V;
11264 
11265   // See if we can use a vector load to get all of the elements.
11266   {
11267     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
11268     if (SDValue LD =
11269             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
11270       return LD;
11271   }
11272 
11273   // If this is a splat of pairs of 32-bit elements, we can use a narrower
11274   // build_vector and broadcast it.
11275   // TODO: We could probably generalize this more.
11276   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
11277     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
11278                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
11279     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
11280       // Make sure all the even/odd operands match.
11281       for (unsigned i = 2; i != NumElems; ++i)
11282         if (Ops[i % 2] != Op.getOperand(i))
11283           return false;
11284       return true;
11285     };
11286     if (CanSplat(Op, NumElems, Ops)) {
11287       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
11288       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
11289       // Create a new build vector and cast to v2i64/v2f64.
11290       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
11291                                      DAG.getBuildVector(NarrowVT, dl, Ops));
11292       // Broadcast from v2i64/v2f64 and cast to final VT.
11293       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
11294       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
11295                                             NewBV));
11296     }
11297   }
11298 
11299   // For AVX-length vectors, build the individual 128-bit pieces and use
11300   // shuffles to put them in place.
11301   if (VT.getSizeInBits() > 128) {
11302     MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
11303 
11304     // Build both the lower and upper subvector.
11305     SDValue Lower =
11306         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
11307     SDValue Upper = DAG.getBuildVector(
11308         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
11309 
11310     // Recreate the wider vector with the lower and upper part.
11311     return concatSubVectors(Lower, Upper, DAG, dl);
11312   }
11313 
11314   // Let legalizer expand 2-wide build_vectors.
11315   if (EVTBits == 64) {
11316     if (NumNonZero == 1) {
11317       // One half is zero or undef.
11318       unsigned Idx = NonZeroMask.countTrailingZeros();
11319       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
11320                                Op.getOperand(Idx));
11321       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
11322     }
11323     return SDValue();
11324   }
11325 
11326   // If element VT is < 32 bits, convert it to inserts into a zero vector.
11327   if (EVTBits == 8 && NumElems == 16)
11328     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeroMask, NumNonZero, NumZero,
11329                                           DAG, Subtarget))
11330       return V;
11331 
11332   if (EltVT == MVT::i16 && NumElems == 8)
11333     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeroMask, NumNonZero, NumZero,
11334                                           DAG, Subtarget))
11335       return V;
11336 
11337   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
11338   if (EVTBits == 32 && NumElems == 4)
11339     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
11340       return V;
11341 
11342   // If element VT is == 32 bits, turn it into a number of shuffles.
11343   if (NumElems == 4 && NumZero > 0) {
11344     SmallVector<SDValue, 8> Ops(NumElems);
11345     for (unsigned i = 0; i < 4; ++i) {
11346       bool isZero = !NonZeroMask[i];
11347       if (isZero)
11348         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
11349       else
11350         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
11351     }
11352 
11353     for (unsigned i = 0; i < 2; ++i) {
11354       switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
11355         default: llvm_unreachable("Unexpected NonZero count");
11356         case 0:
11357           Ops[i] = Ops[i*2];  // Must be a zero vector.
11358           break;
11359         case 1:
11360           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
11361           break;
11362         case 2:
11363           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
11364           break;
11365         case 3:
11366           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
11367           break;
11368       }
11369     }
11370 
11371     bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
11372     bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
11373     int MaskVec[] = {
11374       Reverse1 ? 1 : 0,
11375       Reverse1 ? 0 : 1,
11376       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
11377       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
11378     };
11379     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
11380   }
11381 
11382   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
11383 
11384   // Check for a build vector from mostly shuffle plus few inserting.
11385   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
11386     return Sh;
11387 
11388   // For SSE 4.1, use insertps to put the high elements into the low element.
11389   if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
11390     SDValue Result;
11391     if (!Op.getOperand(0).isUndef())
11392       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
11393     else
11394       Result = DAG.getUNDEF(VT);
11395 
11396     for (unsigned i = 1; i < NumElems; ++i) {
11397       if (Op.getOperand(i).isUndef()) continue;
11398       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
11399                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
11400     }
11401     return Result;
11402   }
11403 
11404   // Otherwise, expand into a number of unpckl*, start by extending each of
11405   // our (non-undef) elements to the full vector width with the element in the
11406   // bottom slot of the vector (which generates no code for SSE).
11407   SmallVector<SDValue, 8> Ops(NumElems);
11408   for (unsigned i = 0; i < NumElems; ++i) {
11409     if (!Op.getOperand(i).isUndef())
11410       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
11411     else
11412       Ops[i] = DAG.getUNDEF(VT);
11413   }
11414 
11415   // Next, we iteratively mix elements, e.g. for v4f32:
11416   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
11417   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
11418   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
11419   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
11420     // Generate scaled UNPCKL shuffle mask.
11421     SmallVector<int, 16> Mask;
11422     for(unsigned i = 0; i != Scale; ++i)
11423       Mask.push_back(i);
11424     for (unsigned i = 0; i != Scale; ++i)
11425       Mask.push_back(NumElems+i);
11426     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
11427 
11428     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
11429       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
11430   }
11431   return Ops[0];
11432 }
11433 
11434 // 256-bit AVX can use the vinsertf128 instruction
11435 // to create 256-bit vectors from two other 128-bit ones.
11436 // TODO: Detect subvector broadcast here instead of DAG combine?
11437 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
11438                                       const X86Subtarget &Subtarget) {
11439   SDLoc dl(Op);
11440   MVT ResVT = Op.getSimpleValueType();
11441 
11442   assert((ResVT.is256BitVector() ||
11443           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
11444 
11445   unsigned NumOperands = Op.getNumOperands();
11446   unsigned NumZero = 0;
11447   unsigned NumNonZero = 0;
11448   unsigned NonZeros = 0;
11449   for (unsigned i = 0; i != NumOperands; ++i) {
11450     SDValue SubVec = Op.getOperand(i);
11451     if (SubVec.isUndef())
11452       continue;
11453     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
11454       ++NumZero;
11455     else {
11456       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
11457       NonZeros |= 1 << i;
11458       ++NumNonZero;
11459     }
11460   }
11461 
11462   // If we have more than 2 non-zeros, build each half separately.
11463   if (NumNonZero > 2) {
11464     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
11465     ArrayRef<SDUse> Ops = Op->ops();
11466     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11467                              Ops.slice(0, NumOperands/2));
11468     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11469                              Ops.slice(NumOperands/2));
11470     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
11471   }
11472 
11473   // Otherwise, build it up through insert_subvectors.
11474   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
11475                         : DAG.getUNDEF(ResVT);
11476 
11477   MVT SubVT = Op.getOperand(0).getSimpleValueType();
11478   unsigned NumSubElems = SubVT.getVectorNumElements();
11479   for (unsigned i = 0; i != NumOperands; ++i) {
11480     if ((NonZeros & (1 << i)) == 0)
11481       continue;
11482 
11483     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
11484                       Op.getOperand(i),
11485                       DAG.getIntPtrConstant(i * NumSubElems, dl));
11486   }
11487 
11488   return Vec;
11489 }
11490 
11491 // Returns true if the given node is a type promotion (by concatenating i1
11492 // zeros) of the result of a node that already zeros all upper bits of
11493 // k-register.
11494 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
11495 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
11496                                        const X86Subtarget &Subtarget,
11497                                        SelectionDAG & DAG) {
11498   SDLoc dl(Op);
11499   MVT ResVT = Op.getSimpleValueType();
11500   unsigned NumOperands = Op.getNumOperands();
11501 
11502   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
11503          "Unexpected number of operands in CONCAT_VECTORS");
11504 
11505   uint64_t Zeros = 0;
11506   uint64_t NonZeros = 0;
11507   for (unsigned i = 0; i != NumOperands; ++i) {
11508     SDValue SubVec = Op.getOperand(i);
11509     if (SubVec.isUndef())
11510       continue;
11511     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
11512     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
11513       Zeros |= (uint64_t)1 << i;
11514     else
11515       NonZeros |= (uint64_t)1 << i;
11516   }
11517 
11518   unsigned NumElems = ResVT.getVectorNumElements();
11519 
11520   // If we are inserting non-zero vector and there are zeros in LSBs and undef
11521   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
11522   // insert_subvector will give us two kshifts.
11523   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
11524       Log2_64(NonZeros) != NumOperands - 1) {
11525     MVT ShiftVT = ResVT;
11526     if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
11527       ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
11528     unsigned Idx = Log2_64(NonZeros);
11529     SDValue SubVec = Op.getOperand(Idx);
11530     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
11531     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
11532                          DAG.getUNDEF(ShiftVT), SubVec,
11533                          DAG.getIntPtrConstant(0, dl));
11534     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
11535                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
11536     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
11537                        DAG.getIntPtrConstant(0, dl));
11538   }
11539 
11540   // If there are zero or one non-zeros we can handle this very simply.
11541   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
11542     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
11543     if (!NonZeros)
11544       return Vec;
11545     unsigned Idx = Log2_64(NonZeros);
11546     SDValue SubVec = Op.getOperand(Idx);
11547     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
11548     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
11549                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
11550   }
11551 
11552   if (NumOperands > 2) {
11553     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
11554     ArrayRef<SDUse> Ops = Op->ops();
11555     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11556                              Ops.slice(0, NumOperands/2));
11557     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11558                              Ops.slice(NumOperands/2));
11559     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
11560   }
11561 
11562   assert(countPopulation(NonZeros) == 2 && "Simple cases not handled?");
11563 
11564   if (ResVT.getVectorNumElements() >= 16)
11565     return Op; // The operation is legal with KUNPCK
11566 
11567   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
11568                             DAG.getUNDEF(ResVT), Op.getOperand(0),
11569                             DAG.getIntPtrConstant(0, dl));
11570   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
11571                      DAG.getIntPtrConstant(NumElems/2, dl));
11572 }
11573 
11574 static SDValue LowerCONCAT_VECTORS(SDValue Op,
11575                                    const X86Subtarget &Subtarget,
11576                                    SelectionDAG &DAG) {
11577   MVT VT = Op.getSimpleValueType();
11578   if (VT.getVectorElementType() == MVT::i1)
11579     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
11580 
11581   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
11582          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
11583           Op.getNumOperands() == 4)));
11584 
11585   // AVX can use the vinsertf128 instruction to create 256-bit vectors
11586   // from two other 128-bit ones.
11587 
11588   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
11589   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
11590 }
11591 
11592 //===----------------------------------------------------------------------===//
11593 // Vector shuffle lowering
11594 //
11595 // This is an experimental code path for lowering vector shuffles on x86. It is
11596 // designed to handle arbitrary vector shuffles and blends, gracefully
11597 // degrading performance as necessary. It works hard to recognize idiomatic
11598 // shuffles and lower them to optimal instruction patterns without leaving
11599 // a framework that allows reasonably efficient handling of all vector shuffle
11600 // patterns.
11601 //===----------------------------------------------------------------------===//
11602 
11603 /// Tiny helper function to identify a no-op mask.
11604 ///
11605 /// This is a somewhat boring predicate function. It checks whether the mask
11606 /// array input, which is assumed to be a single-input shuffle mask of the kind
11607 /// used by the X86 shuffle instructions (not a fully general
11608 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
11609 /// in-place shuffle are 'no-op's.
11610 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
11611   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11612     assert(Mask[i] >= -1 && "Out of bound mask element!");
11613     if (Mask[i] >= 0 && Mask[i] != i)
11614       return false;
11615   }
11616   return true;
11617 }
11618 
11619 /// Test whether there are elements crossing LaneSizeInBits lanes in this
11620 /// shuffle mask.
11621 ///
11622 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
11623 /// and we routinely test for these.
11624 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
11625                                       unsigned ScalarSizeInBits,
11626                                       ArrayRef<int> Mask) {
11627   assert(LaneSizeInBits && ScalarSizeInBits &&
11628          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
11629          "Illegal shuffle lane size");
11630   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
11631   int Size = Mask.size();
11632   for (int i = 0; i < Size; ++i)
11633     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
11634       return true;
11635   return false;
11636 }
11637 
11638 /// Test whether there are elements crossing 128-bit lanes in this
11639 /// shuffle mask.
11640 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
11641   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
11642 }
11643 
11644 /// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
11645 /// from multiple lanes - this is different to isLaneCrossingShuffleMask to
11646 /// better support 'repeated mask + lane permute' style shuffles.
11647 static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
11648                                    unsigned ScalarSizeInBits,
11649                                    ArrayRef<int> Mask) {
11650   assert(LaneSizeInBits && ScalarSizeInBits &&
11651          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
11652          "Illegal shuffle lane size");
11653   int NumElts = Mask.size();
11654   int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
11655   int NumLanes = NumElts / NumEltsPerLane;
11656   if (NumLanes > 1) {
11657     for (int i = 0; i != NumLanes; ++i) {
11658       int SrcLane = -1;
11659       for (int j = 0; j != NumEltsPerLane; ++j) {
11660         int M = Mask[(i * NumEltsPerLane) + j];
11661         if (M < 0)
11662           continue;
11663         int Lane = (M % NumElts) / NumEltsPerLane;
11664         if (SrcLane >= 0 && SrcLane != Lane)
11665           return true;
11666         SrcLane = Lane;
11667       }
11668     }
11669   }
11670   return false;
11671 }
11672 
11673 /// Test whether a shuffle mask is equivalent within each sub-lane.
11674 ///
11675 /// This checks a shuffle mask to see if it is performing the same
11676 /// lane-relative shuffle in each sub-lane. This trivially implies
11677 /// that it is also not lane-crossing. It may however involve a blend from the
11678 /// same lane of a second vector.
11679 ///
11680 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
11681 /// non-trivial to compute in the face of undef lanes. The representation is
11682 /// suitable for use with existing 128-bit shuffles as entries from the second
11683 /// vector have been remapped to [LaneSize, 2*LaneSize).
11684 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
11685                                   ArrayRef<int> Mask,
11686                                   SmallVectorImpl<int> &RepeatedMask) {
11687   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
11688   RepeatedMask.assign(LaneSize, -1);
11689   int Size = Mask.size();
11690   for (int i = 0; i < Size; ++i) {
11691     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
11692     if (Mask[i] < 0)
11693       continue;
11694     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
11695       // This entry crosses lanes, so there is no way to model this shuffle.
11696       return false;
11697 
11698     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
11699     // Adjust second vector indices to start at LaneSize instead of Size.
11700     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
11701                                 : Mask[i] % LaneSize + LaneSize;
11702     if (RepeatedMask[i % LaneSize] < 0)
11703       // This is the first non-undef entry in this slot of a 128-bit lane.
11704       RepeatedMask[i % LaneSize] = LocalM;
11705     else if (RepeatedMask[i % LaneSize] != LocalM)
11706       // Found a mismatch with the repeated mask.
11707       return false;
11708   }
11709   return true;
11710 }
11711 
11712 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
11713 static bool
11714 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
11715                                 SmallVectorImpl<int> &RepeatedMask) {
11716   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
11717 }
11718 
11719 static bool
11720 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
11721   SmallVector<int, 32> RepeatedMask;
11722   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
11723 }
11724 
11725 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
11726 static bool
11727 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
11728                                 SmallVectorImpl<int> &RepeatedMask) {
11729   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
11730 }
11731 
11732 /// Test whether a target shuffle mask is equivalent within each sub-lane.
11733 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
11734 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
11735                                         unsigned EltSizeInBits,
11736                                         ArrayRef<int> Mask,
11737                                         SmallVectorImpl<int> &RepeatedMask) {
11738   int LaneSize = LaneSizeInBits / EltSizeInBits;
11739   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
11740   int Size = Mask.size();
11741   for (int i = 0; i < Size; ++i) {
11742     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
11743     if (Mask[i] == SM_SentinelUndef)
11744       continue;
11745     if (Mask[i] == SM_SentinelZero) {
11746       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
11747         return false;
11748       RepeatedMask[i % LaneSize] = SM_SentinelZero;
11749       continue;
11750     }
11751     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
11752       // This entry crosses lanes, so there is no way to model this shuffle.
11753       return false;
11754 
11755     // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
11756     // later vector indices to start at multiples of LaneSize instead of Size.
11757     int LaneM = Mask[i] / Size;
11758     int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
11759     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
11760       // This is the first non-undef entry in this slot of a 128-bit lane.
11761       RepeatedMask[i % LaneSize] = LocalM;
11762     else if (RepeatedMask[i % LaneSize] != LocalM)
11763       // Found a mismatch with the repeated mask.
11764       return false;
11765   }
11766   return true;
11767 }
11768 
11769 /// Test whether a target shuffle mask is equivalent within each sub-lane.
11770 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
11771 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
11772                                         ArrayRef<int> Mask,
11773                                         SmallVectorImpl<int> &RepeatedMask) {
11774   return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
11775                                      Mask, RepeatedMask);
11776 }
11777 
11778 /// Checks whether the vector elements referenced by two shuffle masks are
11779 /// equivalent.
11780 static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
11781                                 int Idx, int ExpectedIdx) {
11782   assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
11783          ExpectedIdx < MaskSize && "Out of range element index");
11784   if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
11785     return false;
11786 
11787   switch (Op.getOpcode()) {
11788   case ISD::BUILD_VECTOR:
11789     // If the values are build vectors, we can look through them to find
11790     // equivalent inputs that make the shuffles equivalent.
11791     // TODO: Handle MaskSize != Op.getNumOperands()?
11792     if (MaskSize == (int)Op.getNumOperands() &&
11793         MaskSize == (int)ExpectedOp.getNumOperands())
11794       return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
11795     break;
11796   case X86ISD::VBROADCAST:
11797   case X86ISD::VBROADCAST_LOAD:
11798     // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
11799     return (Op == ExpectedOp &&
11800             (int)Op.getValueType().getVectorNumElements() == MaskSize);
11801   case X86ISD::HADD:
11802   case X86ISD::HSUB:
11803   case X86ISD::FHADD:
11804   case X86ISD::FHSUB:
11805   case X86ISD::PACKSS:
11806   case X86ISD::PACKUS:
11807     // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
11808     // TODO: Handle MaskSize != NumElts?
11809     // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
11810     if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
11811       MVT VT = Op.getSimpleValueType();
11812       int NumElts = VT.getVectorNumElements();
11813       if (MaskSize == NumElts) {
11814         int NumLanes = VT.getSizeInBits() / 128;
11815         int NumEltsPerLane = NumElts / NumLanes;
11816         int NumHalfEltsPerLane = NumEltsPerLane / 2;
11817         bool SameLane =
11818             (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
11819         bool SameElt =
11820             (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
11821         return SameLane && SameElt;
11822       }
11823     }
11824     break;
11825   }
11826 
11827   return false;
11828 }
11829 
11830 /// Checks whether a shuffle mask is equivalent to an explicit list of
11831 /// arguments.
11832 ///
11833 /// This is a fast way to test a shuffle mask against a fixed pattern:
11834 ///
11835 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
11836 ///
11837 /// It returns true if the mask is exactly as wide as the argument list, and
11838 /// each element of the mask is either -1 (signifying undef) or the value given
11839 /// in the argument.
11840 static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
11841                                 SDValue V1 = SDValue(),
11842                                 SDValue V2 = SDValue()) {
11843   int Size = Mask.size();
11844   if (Size != (int)ExpectedMask.size())
11845     return false;
11846 
11847   for (int i = 0; i < Size; ++i) {
11848     assert(Mask[i] >= -1 && "Out of bound mask element!");
11849     int MaskIdx = Mask[i];
11850     int ExpectedIdx = ExpectedMask[i];
11851     if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
11852       SDValue MaskV = MaskIdx < Size ? V1 : V2;
11853       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11854       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11855       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11856       if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11857         return false;
11858     }
11859   }
11860   return true;
11861 }
11862 
11863 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
11864 ///
11865 /// The masks must be exactly the same width.
11866 ///
11867 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
11868 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
11869 ///
11870 /// SM_SentinelZero is accepted as a valid negative index but must match in
11871 /// both, or via a known bits test.
11872 static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
11873                                       ArrayRef<int> ExpectedMask,
11874                                       const SelectionDAG &DAG,
11875                                       SDValue V1 = SDValue(),
11876                                       SDValue V2 = SDValue()) {
11877   int Size = Mask.size();
11878   if (Size != (int)ExpectedMask.size())
11879     return false;
11880   assert(llvm::all_of(ExpectedMask,
11881                       [Size](int M) { return isInRange(M, 0, 2 * Size); }) &&
11882          "Illegal target shuffle mask");
11883 
11884   // Check for out-of-range target shuffle mask indices.
11885   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
11886     return false;
11887 
11888   // Don't use V1/V2 if they're not the same size as the shuffle mask type.
11889   if (V1 && V1.getValueSizeInBits() != VT.getSizeInBits())
11890     V1 = SDValue();
11891   if (V2 && V2.getValueSizeInBits() != VT.getSizeInBits())
11892     V2 = SDValue();
11893 
11894   APInt ZeroV1 = APInt::getNullValue(Size);
11895   APInt ZeroV2 = APInt::getNullValue(Size);
11896 
11897   for (int i = 0; i < Size; ++i) {
11898     int MaskIdx = Mask[i];
11899     int ExpectedIdx = ExpectedMask[i];
11900     if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
11901       continue;
11902     if (MaskIdx == SM_SentinelZero) {
11903       // If we need this expected index to be a zero element, then update the
11904       // relevant zero mask and perform the known bits at the end to minimize
11905       // repeated computes.
11906       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11907       if (ExpectedV &&
11908           Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
11909         int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11910         APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
11911         ZeroMask.setBit(BitIdx);
11912         continue;
11913       }
11914     }
11915     if (MaskIdx >= 0) {
11916       SDValue MaskV = MaskIdx < Size ? V1 : V2;
11917       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11918       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11919       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11920       if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11921         continue;
11922     }
11923     return false;
11924   }
11925   return (ZeroV1.isNullValue() || DAG.MaskedVectorIsZero(V1, ZeroV1)) &&
11926          (ZeroV2.isNullValue() || DAG.MaskedVectorIsZero(V2, ZeroV2));
11927 }
11928 
11929 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
11930 // instructions.
11931 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT,
11932                                   const SelectionDAG &DAG) {
11933   if (VT != MVT::v8i32 && VT != MVT::v8f32)
11934     return false;
11935 
11936   SmallVector<int, 8> Unpcklwd;
11937   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
11938                           /* Unary = */ false);
11939   SmallVector<int, 8> Unpckhwd;
11940   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
11941                           /* Unary = */ false);
11942   bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
11943                          isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
11944   return IsUnpackwdMask;
11945 }
11946 
11947 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask,
11948                                       const SelectionDAG &DAG) {
11949   // Create 128-bit vector type based on mask size.
11950   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
11951   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
11952 
11953   // We can't assume a canonical shuffle mask, so try the commuted version too.
11954   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
11955   ShuffleVectorSDNode::commuteMask(CommutedMask);
11956 
11957   // Match any of unary/binary or low/high.
11958   for (unsigned i = 0; i != 4; ++i) {
11959     SmallVector<int, 16> UnpackMask;
11960     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
11961     if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
11962         isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
11963       return true;
11964   }
11965   return false;
11966 }
11967 
11968 /// Return true if a shuffle mask chooses elements identically in its top and
11969 /// bottom halves. For example, any splat mask has the same top and bottom
11970 /// halves. If an element is undefined in only one half of the mask, the halves
11971 /// are not considered identical.
11972 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
11973   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
11974   unsigned HalfSize = Mask.size() / 2;
11975   for (unsigned i = 0; i != HalfSize; ++i) {
11976     if (Mask[i] != Mask[i + HalfSize])
11977       return false;
11978   }
11979   return true;
11980 }
11981 
11982 /// Get a 4-lane 8-bit shuffle immediate for a mask.
11983 ///
11984 /// This helper function produces an 8-bit shuffle immediate corresponding to
11985 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
11986 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
11987 /// example.
11988 ///
11989 /// NB: We rely heavily on "undef" masks preserving the input lane.
11990 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
11991   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
11992   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
11993   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
11994   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
11995   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
11996 
11997   // If the mask only uses one non-undef element, then fully 'splat' it to
11998   // improve later broadcast matching.
11999   int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
12000   assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
12001 
12002   int FirstElt = Mask[FirstIndex];
12003   if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
12004     return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
12005 
12006   unsigned Imm = 0;
12007   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
12008   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
12009   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
12010   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
12011   return Imm;
12012 }
12013 
12014 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
12015                                           SelectionDAG &DAG) {
12016   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
12017 }
12018 
12019 // The Shuffle result is as follow:
12020 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
12021 // Each Zeroable's element correspond to a particular Mask's element.
12022 // As described in computeZeroableShuffleElements function.
12023 //
12024 // The function looks for a sub-mask that the nonzero elements are in
12025 // increasing order. If such sub-mask exist. The function returns true.
12026 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
12027                                      ArrayRef<int> Mask, const EVT &VectorType,
12028                                      bool &IsZeroSideLeft) {
12029   int NextElement = -1;
12030   // Check if the Mask's nonzero elements are in increasing order.
12031   for (int i = 0, e = Mask.size(); i < e; i++) {
12032     // Checks if the mask's zeros elements are built from only zeros.
12033     assert(Mask[i] >= -1 && "Out of bound mask element!");
12034     if (Mask[i] < 0)
12035       return false;
12036     if (Zeroable[i])
12037       continue;
12038     // Find the lowest non zero element
12039     if (NextElement < 0) {
12040       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
12041       IsZeroSideLeft = NextElement != 0;
12042     }
12043     // Exit if the mask's non zero elements are not in increasing order.
12044     if (NextElement != Mask[i])
12045       return false;
12046     NextElement++;
12047   }
12048   return true;
12049 }
12050 
12051 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
12052 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
12053                                       ArrayRef<int> Mask, SDValue V1,
12054                                       SDValue V2, const APInt &Zeroable,
12055                                       const X86Subtarget &Subtarget,
12056                                       SelectionDAG &DAG) {
12057   int Size = Mask.size();
12058   int LaneSize = 128 / VT.getScalarSizeInBits();
12059   const int NumBytes = VT.getSizeInBits() / 8;
12060   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
12061 
12062   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
12063          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
12064          (Subtarget.hasBWI() && VT.is512BitVector()));
12065 
12066   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
12067   // Sign bit set in i8 mask means zero element.
12068   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
12069 
12070   SDValue V;
12071   for (int i = 0; i < NumBytes; ++i) {
12072     int M = Mask[i / NumEltBytes];
12073     if (M < 0) {
12074       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
12075       continue;
12076     }
12077     if (Zeroable[i / NumEltBytes]) {
12078       PSHUFBMask[i] = ZeroMask;
12079       continue;
12080     }
12081 
12082     // We can only use a single input of V1 or V2.
12083     SDValue SrcV = (M >= Size ? V2 : V1);
12084     if (V && V != SrcV)
12085       return SDValue();
12086     V = SrcV;
12087     M %= Size;
12088 
12089     // PSHUFB can't cross lanes, ensure this doesn't happen.
12090     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
12091       return SDValue();
12092 
12093     M = M % LaneSize;
12094     M = M * NumEltBytes + (i % NumEltBytes);
12095     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
12096   }
12097   assert(V && "Failed to find a source input");
12098 
12099   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
12100   return DAG.getBitcast(
12101       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
12102                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
12103 }
12104 
12105 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
12106                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
12107                            const SDLoc &dl);
12108 
12109 // X86 has dedicated shuffle that can be lowered to VEXPAND
12110 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
12111                                     const APInt &Zeroable,
12112                                     ArrayRef<int> Mask, SDValue &V1,
12113                                     SDValue &V2, SelectionDAG &DAG,
12114                                     const X86Subtarget &Subtarget) {
12115   bool IsLeftZeroSide = true;
12116   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
12117                                 IsLeftZeroSide))
12118     return SDValue();
12119   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
12120   MVT IntegerType =
12121       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12122   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
12123   unsigned NumElts = VT.getVectorNumElements();
12124   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
12125          "Unexpected number of vector elements");
12126   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
12127                               Subtarget, DAG, DL);
12128   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
12129   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
12130   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
12131 }
12132 
12133 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
12134                                   unsigned &UnpackOpcode, bool IsUnary,
12135                                   ArrayRef<int> TargetMask, const SDLoc &DL,
12136                                   SelectionDAG &DAG,
12137                                   const X86Subtarget &Subtarget) {
12138   int NumElts = VT.getVectorNumElements();
12139 
12140   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
12141   for (int i = 0; i != NumElts; i += 2) {
12142     int M1 = TargetMask[i + 0];
12143     int M2 = TargetMask[i + 1];
12144     Undef1 &= (SM_SentinelUndef == M1);
12145     Undef2 &= (SM_SentinelUndef == M2);
12146     Zero1 &= isUndefOrZero(M1);
12147     Zero2 &= isUndefOrZero(M2);
12148   }
12149   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
12150          "Zeroable shuffle detected");
12151 
12152   // Attempt to match the target mask against the unpack lo/hi mask patterns.
12153   SmallVector<int, 64> Unpckl, Unpckh;
12154   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
12155   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
12156                                 (IsUnary ? V1 : V2))) {
12157     UnpackOpcode = X86ISD::UNPCKL;
12158     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
12159     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
12160     return true;
12161   }
12162 
12163   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
12164   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
12165                                 (IsUnary ? V1 : V2))) {
12166     UnpackOpcode = X86ISD::UNPCKH;
12167     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
12168     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
12169     return true;
12170   }
12171 
12172   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
12173   if (IsUnary && (Zero1 || Zero2)) {
12174     // Don't bother if we can blend instead.
12175     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
12176         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
12177       return false;
12178 
12179     bool MatchLo = true, MatchHi = true;
12180     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
12181       int M = TargetMask[i];
12182 
12183       // Ignore if the input is known to be zero or the index is undef.
12184       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
12185           (M == SM_SentinelUndef))
12186         continue;
12187 
12188       MatchLo &= (M == Unpckl[i]);
12189       MatchHi &= (M == Unpckh[i]);
12190     }
12191 
12192     if (MatchLo || MatchHi) {
12193       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
12194       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
12195       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
12196       return true;
12197     }
12198   }
12199 
12200   // If a binary shuffle, commute and try again.
12201   if (!IsUnary) {
12202     ShuffleVectorSDNode::commuteMask(Unpckl);
12203     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
12204       UnpackOpcode = X86ISD::UNPCKL;
12205       std::swap(V1, V2);
12206       return true;
12207     }
12208 
12209     ShuffleVectorSDNode::commuteMask(Unpckh);
12210     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
12211       UnpackOpcode = X86ISD::UNPCKH;
12212       std::swap(V1, V2);
12213       return true;
12214     }
12215   }
12216 
12217   return false;
12218 }
12219 
12220 // X86 has dedicated unpack instructions that can handle specific blend
12221 // operations: UNPCKH and UNPCKL.
12222 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
12223                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
12224                                      SelectionDAG &DAG) {
12225   SmallVector<int, 8> Unpckl;
12226   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
12227   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
12228     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
12229 
12230   SmallVector<int, 8> Unpckh;
12231   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
12232   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
12233     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
12234 
12235   // Commute and try again.
12236   ShuffleVectorSDNode::commuteMask(Unpckl);
12237   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
12238     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
12239 
12240   ShuffleVectorSDNode::commuteMask(Unpckh);
12241   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
12242     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
12243 
12244   return SDValue();
12245 }
12246 
12247 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
12248 /// followed by unpack 256-bit.
12249 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
12250                                         ArrayRef<int> Mask, SDValue V1,
12251                                         SDValue V2, SelectionDAG &DAG) {
12252   SmallVector<int, 32> Unpckl, Unpckh;
12253   createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
12254   createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
12255 
12256   unsigned UnpackOpcode;
12257   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
12258     UnpackOpcode = X86ISD::UNPCKL;
12259   else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
12260     UnpackOpcode = X86ISD::UNPCKH;
12261   else
12262     return SDValue();
12263 
12264   // This is a "natural" unpack operation (rather than the 128-bit sectored
12265   // operation implemented by AVX). We need to rearrange 64-bit chunks of the
12266   // input in order to use the x86 instruction.
12267   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
12268                             DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
12269   V1 = DAG.getBitcast(VT, V1);
12270   return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
12271 }
12272 
12273 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
12274 // source into the lower elements and zeroing the upper elements.
12275 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
12276                                  ArrayRef<int> Mask, const APInt &Zeroable,
12277                                  const X86Subtarget &Subtarget) {
12278   if (!VT.is512BitVector() && !Subtarget.hasVLX())
12279     return false;
12280 
12281   unsigned NumElts = Mask.size();
12282   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12283   unsigned MaxScale = 64 / EltSizeInBits;
12284 
12285   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12286     unsigned SrcEltBits = EltSizeInBits * Scale;
12287     if (SrcEltBits < 32 && !Subtarget.hasBWI())
12288       continue;
12289     unsigned NumSrcElts = NumElts / Scale;
12290     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
12291       continue;
12292     unsigned UpperElts = NumElts - NumSrcElts;
12293     if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12294       continue;
12295     SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
12296     SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
12297     DstVT = MVT::getIntegerVT(EltSizeInBits);
12298     if ((NumSrcElts * EltSizeInBits) >= 128) {
12299       // ISD::TRUNCATE
12300       DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
12301     } else {
12302       // X86ISD::VTRUNC
12303       DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
12304     }
12305     return true;
12306   }
12307 
12308   return false;
12309 }
12310 
12311 // Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
12312 // element padding to the final DstVT.
12313 static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
12314                                   const X86Subtarget &Subtarget,
12315                                   SelectionDAG &DAG, bool ZeroUppers) {
12316   MVT SrcVT = Src.getSimpleValueType();
12317   MVT DstSVT = DstVT.getScalarType();
12318   unsigned NumDstElts = DstVT.getVectorNumElements();
12319   unsigned NumSrcElts = SrcVT.getVectorNumElements();
12320   unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
12321 
12322   if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
12323     return SDValue();
12324 
12325   // Perform a direct ISD::TRUNCATE if possible.
12326   if (NumSrcElts == NumDstElts)
12327     return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
12328 
12329   if (NumSrcElts > NumDstElts) {
12330     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
12331     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
12332     return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
12333   }
12334 
12335   if ((NumSrcElts * DstEltSizeInBits) >= 128) {
12336     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
12337     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
12338     return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
12339                           DstVT.getSizeInBits());
12340   }
12341 
12342   // Non-VLX targets must truncate from a 512-bit type, so we need to
12343   // widen, truncate and then possibly extract the original subvector.
12344   if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
12345     SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
12346     return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
12347   }
12348 
12349   // Fallback to a X86ISD::VTRUNC, padding if necessary.
12350   MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
12351   SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
12352   if (DstVT != TruncVT)
12353     Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
12354                            DstVT.getSizeInBits());
12355   return Trunc;
12356 }
12357 
12358 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
12359 //
12360 // An example is the following:
12361 //
12362 // t0: ch = EntryToken
12363 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
12364 //         t25: v4i32 = truncate t2
12365 //       t41: v8i16 = bitcast t25
12366 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
12367 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
12368 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
12369 //   t18: v2i64 = bitcast t51
12370 //
12371 // One can just use a single vpmovdw instruction, without avx512vl we need to
12372 // use the zmm variant and extract the lower subvector, padding with zeroes.
12373 // TODO: Merge with lowerShuffleAsVTRUNC.
12374 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
12375                                      SDValue V2, ArrayRef<int> Mask,
12376                                      const APInt &Zeroable,
12377                                      const X86Subtarget &Subtarget,
12378                                      SelectionDAG &DAG) {
12379   assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
12380   if (!Subtarget.hasAVX512())
12381     return SDValue();
12382 
12383   unsigned NumElts = VT.getVectorNumElements();
12384   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12385   unsigned MaxScale = 64 / EltSizeInBits;
12386   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12387     unsigned NumSrcElts = NumElts / Scale;
12388     unsigned UpperElts = NumElts - NumSrcElts;
12389     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
12390         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12391       continue;
12392 
12393     SDValue Src = V1;
12394     if (!Src.hasOneUse())
12395       return SDValue();
12396 
12397     Src = peekThroughOneUseBitcasts(Src);
12398     if (Src.getOpcode() != ISD::TRUNCATE ||
12399         Src.getScalarValueSizeInBits() != (EltSizeInBits * Scale))
12400       return SDValue();
12401     Src = Src.getOperand(0);
12402 
12403     // VPMOVWB is only available with avx512bw.
12404     MVT SrcVT = Src.getSimpleValueType();
12405     if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
12406         !Subtarget.hasBWI())
12407       return SDValue();
12408 
12409     bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
12410     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
12411   }
12412 
12413   return SDValue();
12414 }
12415 
12416 // Attempt to match binary shuffle patterns as a truncate.
12417 static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
12418                                     SDValue V2, ArrayRef<int> Mask,
12419                                     const APInt &Zeroable,
12420                                     const X86Subtarget &Subtarget,
12421                                     SelectionDAG &DAG) {
12422   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12423          "Unexpected VTRUNC type");
12424   if (!Subtarget.hasAVX512())
12425     return SDValue();
12426 
12427   unsigned NumElts = VT.getVectorNumElements();
12428   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12429   unsigned MaxScale = 64 / EltSizeInBits;
12430   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12431     // TODO: Support non-BWI VPMOVWB truncations?
12432     unsigned SrcEltBits = EltSizeInBits * Scale;
12433     if (SrcEltBits < 32 && !Subtarget.hasBWI())
12434       continue;
12435 
12436     // Match shuffle <0,Scale,2*Scale,..,undef_or_zero,undef_or_zero,...>
12437     // Bail if the V2 elements are undef.
12438     unsigned NumHalfSrcElts = NumElts / Scale;
12439     unsigned NumSrcElts = 2 * NumHalfSrcElts;
12440     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
12441         isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
12442       continue;
12443 
12444     // The elements beyond the truncation must be undef/zero.
12445     unsigned UpperElts = NumElts - NumSrcElts;
12446     if (UpperElts > 0 &&
12447         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12448       continue;
12449     bool UndefUppers =
12450         UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
12451 
12452     // As we're using both sources then we need to concat them together
12453     // and truncate from the double-sized src.
12454     MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
12455     SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
12456 
12457     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
12458     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
12459     Src = DAG.getBitcast(SrcVT, Src);
12460     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
12461   }
12462 
12463   return SDValue();
12464 }
12465 
12466 /// Check whether a compaction lowering can be done by dropping even/odd
12467 /// elements and compute how many times even/odd elements must be dropped.
12468 ///
12469 /// This handles shuffles which take every Nth element where N is a power of
12470 /// two. Example shuffle masks:
12471 ///
12472 /// (even)
12473 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
12474 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
12475 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
12476 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
12477 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
12478 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
12479 ///
12480 /// (odd)
12481 ///  N = 1:  1,  3,  5,  7,  9, 11, 13, 15,  0,  2,  4,  6,  8, 10, 12, 14
12482 ///  N = 1:  1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
12483 ///
12484 /// Any of these lanes can of course be undef.
12485 ///
12486 /// This routine only supports N <= 3.
12487 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
12488 /// for larger N.
12489 ///
12490 /// \returns N above, or the number of times even/odd elements must be dropped
12491 /// if there is such a number. Otherwise returns zero.
12492 static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
12493                                       bool IsSingleInput) {
12494   // The modulus for the shuffle vector entries is based on whether this is
12495   // a single input or not.
12496   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
12497   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
12498          "We should only be called with masks with a power-of-2 size!");
12499 
12500   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
12501   int Offset = MatchEven ? 0 : 1;
12502 
12503   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
12504   // and 2^3 simultaneously. This is because we may have ambiguity with
12505   // partially undef inputs.
12506   bool ViableForN[3] = {true, true, true};
12507 
12508   for (int i = 0, e = Mask.size(); i < e; ++i) {
12509     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
12510     // want.
12511     if (Mask[i] < 0)
12512       continue;
12513 
12514     bool IsAnyViable = false;
12515     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
12516       if (ViableForN[j]) {
12517         uint64_t N = j + 1;
12518 
12519         // The shuffle mask must be equal to (i * 2^N) % M.
12520         if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
12521           IsAnyViable = true;
12522         else
12523           ViableForN[j] = false;
12524       }
12525     // Early exit if we exhaust the possible powers of two.
12526     if (!IsAnyViable)
12527       break;
12528   }
12529 
12530   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
12531     if (ViableForN[j])
12532       return j + 1;
12533 
12534   // Return 0 as there is no viable power of two.
12535   return 0;
12536 }
12537 
12538 // X86 has dedicated pack instructions that can handle specific truncation
12539 // operations: PACKSS and PACKUS.
12540 // Checks for compaction shuffle masks if MaxStages > 1.
12541 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
12542 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
12543                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
12544                                  const SelectionDAG &DAG,
12545                                  const X86Subtarget &Subtarget,
12546                                  unsigned MaxStages = 1) {
12547   unsigned NumElts = VT.getVectorNumElements();
12548   unsigned BitSize = VT.getScalarSizeInBits();
12549   assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
12550          "Illegal maximum compaction");
12551 
12552   auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
12553     unsigned NumSrcBits = PackVT.getScalarSizeInBits();
12554     unsigned NumPackedBits = NumSrcBits - BitSize;
12555     N1 = peekThroughBitcasts(N1);
12556     N2 = peekThroughBitcasts(N2);
12557     unsigned NumBits1 = N1.getScalarValueSizeInBits();
12558     unsigned NumBits2 = N2.getScalarValueSizeInBits();
12559     bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
12560     bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
12561     if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
12562         (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
12563       return false;
12564     if (Subtarget.hasSSE41() || BitSize == 8) {
12565       APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
12566       if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
12567           (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
12568         V1 = N1;
12569         V2 = N2;
12570         SrcVT = PackVT;
12571         PackOpcode = X86ISD::PACKUS;
12572         return true;
12573       }
12574     }
12575     bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
12576     bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
12577     if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
12578          DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
12579         (N2.isUndef() || IsZero2 || IsAllOnes2 ||
12580          DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
12581       V1 = N1;
12582       V2 = N2;
12583       SrcVT = PackVT;
12584       PackOpcode = X86ISD::PACKSS;
12585       return true;
12586     }
12587     return false;
12588   };
12589 
12590   // Attempt to match against wider and wider compaction patterns.
12591   for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
12592     MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
12593     MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
12594 
12595     // Try binary shuffle.
12596     SmallVector<int, 32> BinaryMask;
12597     createPackShuffleMask(VT, BinaryMask, false, NumStages);
12598     if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
12599       if (MatchPACK(V1, V2, PackVT))
12600         return true;
12601 
12602     // Try unary shuffle.
12603     SmallVector<int, 32> UnaryMask;
12604     createPackShuffleMask(VT, UnaryMask, true, NumStages);
12605     if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
12606       if (MatchPACK(V1, V1, PackVT))
12607         return true;
12608   }
12609 
12610   return false;
12611 }
12612 
12613 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
12614                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
12615                                     const X86Subtarget &Subtarget) {
12616   MVT PackVT;
12617   unsigned PackOpcode;
12618   unsigned SizeBits = VT.getSizeInBits();
12619   unsigned EltBits = VT.getScalarSizeInBits();
12620   unsigned MaxStages = Log2_32(64 / EltBits);
12621   if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
12622                             Subtarget, MaxStages))
12623     return SDValue();
12624 
12625   unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
12626   unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
12627 
12628   // Don't lower multi-stage packs on AVX512, truncation is better.
12629   if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
12630     return SDValue();
12631 
12632   // Pack to the largest type possible:
12633   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
12634   unsigned MaxPackBits = 16;
12635   if (CurrentEltBits > 16 &&
12636       (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
12637     MaxPackBits = 32;
12638 
12639   // Repeatedly pack down to the target size.
12640   SDValue Res;
12641   for (unsigned i = 0; i != NumStages; ++i) {
12642     unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
12643     unsigned NumSrcElts = SizeBits / SrcEltBits;
12644     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
12645     MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
12646     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
12647     MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
12648     Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
12649                       DAG.getBitcast(SrcVT, V2));
12650     V1 = V2 = Res;
12651     CurrentEltBits /= 2;
12652   }
12653   assert(Res && Res.getValueType() == VT &&
12654          "Failed to lower compaction shuffle");
12655   return Res;
12656 }
12657 
12658 /// Try to emit a bitmask instruction for a shuffle.
12659 ///
12660 /// This handles cases where we can model a blend exactly as a bitmask due to
12661 /// one of the inputs being zeroable.
12662 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
12663                                      SDValue V2, ArrayRef<int> Mask,
12664                                      const APInt &Zeroable,
12665                                      const X86Subtarget &Subtarget,
12666                                      SelectionDAG &DAG) {
12667   MVT MaskVT = VT;
12668   MVT EltVT = VT.getVectorElementType();
12669   SDValue Zero, AllOnes;
12670   // Use f64 if i64 isn't legal.
12671   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
12672     EltVT = MVT::f64;
12673     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
12674   }
12675 
12676   MVT LogicVT = VT;
12677   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
12678     Zero = DAG.getConstantFP(0.0, DL, EltVT);
12679     APFloat AllOnesValue =
12680         APFloat::getAllOnesValue(SelectionDAG::EVTToAPFloatSemantics(EltVT));
12681     AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
12682     LogicVT =
12683         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
12684   } else {
12685     Zero = DAG.getConstant(0, DL, EltVT);
12686     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
12687   }
12688 
12689   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
12690   SDValue V;
12691   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12692     if (Zeroable[i])
12693       continue;
12694     if (Mask[i] % Size != i)
12695       return SDValue(); // Not a blend.
12696     if (!V)
12697       V = Mask[i] < Size ? V1 : V2;
12698     else if (V != (Mask[i] < Size ? V1 : V2))
12699       return SDValue(); // Can only let one input through the mask.
12700 
12701     VMaskOps[i] = AllOnes;
12702   }
12703   if (!V)
12704     return SDValue(); // No non-zeroable elements!
12705 
12706   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
12707   VMask = DAG.getBitcast(LogicVT, VMask);
12708   V = DAG.getBitcast(LogicVT, V);
12709   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
12710   return DAG.getBitcast(VT, And);
12711 }
12712 
12713 /// Try to emit a blend instruction for a shuffle using bit math.
12714 ///
12715 /// This is used as a fallback approach when first class blend instructions are
12716 /// unavailable. Currently it is only suitable for integer vectors, but could
12717 /// be generalized for floating point vectors if desirable.
12718 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
12719                                       SDValue V2, ArrayRef<int> Mask,
12720                                       SelectionDAG &DAG) {
12721   assert(VT.isInteger() && "Only supports integer vector types!");
12722   MVT EltVT = VT.getVectorElementType();
12723   SDValue Zero = DAG.getConstant(0, DL, EltVT);
12724   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
12725   SmallVector<SDValue, 16> MaskOps;
12726   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12727     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
12728       return SDValue(); // Shuffled input!
12729     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
12730   }
12731 
12732   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
12733   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
12734   V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
12735   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
12736 }
12737 
12738 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
12739                                     SDValue PreservedSrc,
12740                                     const X86Subtarget &Subtarget,
12741                                     SelectionDAG &DAG);
12742 
12743 static bool matchShuffleAsBlend(SDValue V1, SDValue V2,
12744                                 MutableArrayRef<int> Mask,
12745                                 const APInt &Zeroable, bool &ForceV1Zero,
12746                                 bool &ForceV2Zero, uint64_t &BlendMask) {
12747   bool V1IsZeroOrUndef =
12748       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
12749   bool V2IsZeroOrUndef =
12750       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
12751 
12752   BlendMask = 0;
12753   ForceV1Zero = false, ForceV2Zero = false;
12754   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
12755 
12756   // Attempt to generate the binary blend mask. If an input is zero then
12757   // we can use any lane.
12758   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12759     int M = Mask[i];
12760     if (M == SM_SentinelUndef)
12761       continue;
12762     if (M == i ||
12763         (0 <= M && M < Size && IsElementEquivalent(Size, V1, V1, M, i))) {
12764       Mask[i] = i;
12765       continue;
12766     }
12767     if (M == (i + Size) ||
12768         (Size <= M && IsElementEquivalent(Size, V2, V2, M - Size, i))) {
12769       BlendMask |= 1ull << i;
12770       Mask[i] = i + Size;
12771       continue;
12772     }
12773     if (Zeroable[i]) {
12774       if (V1IsZeroOrUndef) {
12775         ForceV1Zero = true;
12776         Mask[i] = i;
12777         continue;
12778       }
12779       if (V2IsZeroOrUndef) {
12780         ForceV2Zero = true;
12781         BlendMask |= 1ull << i;
12782         Mask[i] = i + Size;
12783         continue;
12784       }
12785     }
12786     return false;
12787   }
12788   return true;
12789 }
12790 
12791 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
12792                                             int Scale) {
12793   uint64_t ScaledMask = 0;
12794   for (int i = 0; i != Size; ++i)
12795     if (BlendMask & (1ull << i))
12796       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
12797   return ScaledMask;
12798 }
12799 
12800 /// Try to emit a blend instruction for a shuffle.
12801 ///
12802 /// This doesn't do any checks for the availability of instructions for blending
12803 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
12804 /// be matched in the backend with the type given. What it does check for is
12805 /// that the shuffle mask is a blend, or convertible into a blend with zero.
12806 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
12807                                    SDValue V2, ArrayRef<int> Original,
12808                                    const APInt &Zeroable,
12809                                    const X86Subtarget &Subtarget,
12810                                    SelectionDAG &DAG) {
12811   uint64_t BlendMask = 0;
12812   bool ForceV1Zero = false, ForceV2Zero = false;
12813   SmallVector<int, 64> Mask(Original.begin(), Original.end());
12814   if (!matchShuffleAsBlend(V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
12815                            BlendMask))
12816     return SDValue();
12817 
12818   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
12819   if (ForceV1Zero)
12820     V1 = getZeroVector(VT, Subtarget, DAG, DL);
12821   if (ForceV2Zero)
12822     V2 = getZeroVector(VT, Subtarget, DAG, DL);
12823 
12824   unsigned NumElts = VT.getVectorNumElements();
12825 
12826   switch (VT.SimpleTy) {
12827   case MVT::v4i64:
12828   case MVT::v8i32:
12829     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
12830     LLVM_FALLTHROUGH;
12831   case MVT::v4f64:
12832   case MVT::v8f32:
12833     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
12834     LLVM_FALLTHROUGH;
12835   case MVT::v2f64:
12836   case MVT::v2i64:
12837   case MVT::v4f32:
12838   case MVT::v4i32:
12839   case MVT::v8i16:
12840     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
12841     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
12842                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12843   case MVT::v16i16: {
12844     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
12845     SmallVector<int, 8> RepeatedMask;
12846     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
12847       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
12848       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
12849       BlendMask = 0;
12850       for (int i = 0; i < 8; ++i)
12851         if (RepeatedMask[i] >= 8)
12852           BlendMask |= 1ull << i;
12853       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12854                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12855     }
12856     // Use PBLENDW for lower/upper lanes and then blend lanes.
12857     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
12858     // merge to VSELECT where useful.
12859     uint64_t LoMask = BlendMask & 0xFF;
12860     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
12861     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
12862       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12863                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
12864       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12865                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
12866       return DAG.getVectorShuffle(
12867           MVT::v16i16, DL, Lo, Hi,
12868           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
12869     }
12870     LLVM_FALLTHROUGH;
12871   }
12872   case MVT::v32i8:
12873     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
12874     LLVM_FALLTHROUGH;
12875   case MVT::v16i8: {
12876     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
12877 
12878     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
12879     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12880                                                Subtarget, DAG))
12881       return Masked;
12882 
12883     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
12884       MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
12885       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12886       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12887     }
12888 
12889     // If we have VPTERNLOG, we can use that as a bit blend.
12890     if (Subtarget.hasVLX())
12891       if (SDValue BitBlend =
12892               lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
12893         return BitBlend;
12894 
12895     // Scale the blend by the number of bytes per element.
12896     int Scale = VT.getScalarSizeInBits() / 8;
12897 
12898     // This form of blend is always done on bytes. Compute the byte vector
12899     // type.
12900     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12901 
12902     // x86 allows load folding with blendvb from the 2nd source operand. But
12903     // we are still using LLVM select here (see comment below), so that's V1.
12904     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
12905     // allow that load-folding possibility.
12906     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
12907       ShuffleVectorSDNode::commuteMask(Mask);
12908       std::swap(V1, V2);
12909     }
12910 
12911     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
12912     // mix of LLVM's code generator and the x86 backend. We tell the code
12913     // generator that boolean values in the elements of an x86 vector register
12914     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
12915     // mapping a select to operand #1, and 'false' mapping to operand #2. The
12916     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
12917     // of the element (the remaining are ignored) and 0 in that high bit would
12918     // mean operand #1 while 1 in the high bit would mean operand #2. So while
12919     // the LLVM model for boolean values in vector elements gets the relevant
12920     // bit set, it is set backwards and over constrained relative to x86's
12921     // actual model.
12922     SmallVector<SDValue, 32> VSELECTMask;
12923     for (int i = 0, Size = Mask.size(); i < Size; ++i)
12924       for (int j = 0; j < Scale; ++j)
12925         VSELECTMask.push_back(
12926             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
12927                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
12928                                           MVT::i8));
12929 
12930     V1 = DAG.getBitcast(BlendVT, V1);
12931     V2 = DAG.getBitcast(BlendVT, V2);
12932     return DAG.getBitcast(
12933         VT,
12934         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
12935                       V1, V2));
12936   }
12937   case MVT::v16f32:
12938   case MVT::v8f64:
12939   case MVT::v8i64:
12940   case MVT::v16i32:
12941   case MVT::v32i16:
12942   case MVT::v64i8: {
12943     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
12944     bool OptForSize = DAG.shouldOptForSize();
12945     if (!OptForSize) {
12946       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12947                                                  Subtarget, DAG))
12948         return Masked;
12949     }
12950 
12951     // Otherwise load an immediate into a GPR, cast to k-register, and use a
12952     // masked move.
12953     MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
12954     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12955     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12956   }
12957   default:
12958     llvm_unreachable("Not a supported integer vector type!");
12959   }
12960 }
12961 
12962 /// Try to lower as a blend of elements from two inputs followed by
12963 /// a single-input permutation.
12964 ///
12965 /// This matches the pattern where we can blend elements from two inputs and
12966 /// then reduce the shuffle to a single-input permutation.
12967 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
12968                                              SDValue V1, SDValue V2,
12969                                              ArrayRef<int> Mask,
12970                                              SelectionDAG &DAG,
12971                                              bool ImmBlends = false) {
12972   // We build up the blend mask while checking whether a blend is a viable way
12973   // to reduce the shuffle.
12974   SmallVector<int, 32> BlendMask(Mask.size(), -1);
12975   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
12976 
12977   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12978     if (Mask[i] < 0)
12979       continue;
12980 
12981     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
12982 
12983     if (BlendMask[Mask[i] % Size] < 0)
12984       BlendMask[Mask[i] % Size] = Mask[i];
12985     else if (BlendMask[Mask[i] % Size] != Mask[i])
12986       return SDValue(); // Can't blend in the needed input!
12987 
12988     PermuteMask[i] = Mask[i] % Size;
12989   }
12990 
12991   // If only immediate blends, then bail if the blend mask can't be widened to
12992   // i16.
12993   unsigned EltSize = VT.getScalarSizeInBits();
12994   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
12995     return SDValue();
12996 
12997   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
12998   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
12999 }
13000 
13001 /// Try to lower as an unpack of elements from two inputs followed by
13002 /// a single-input permutation.
13003 ///
13004 /// This matches the pattern where we can unpack elements from two inputs and
13005 /// then reduce the shuffle to a single-input (wider) permutation.
13006 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
13007                                              SDValue V1, SDValue V2,
13008                                              ArrayRef<int> Mask,
13009                                              SelectionDAG &DAG) {
13010   int NumElts = Mask.size();
13011   int NumLanes = VT.getSizeInBits() / 128;
13012   int NumLaneElts = NumElts / NumLanes;
13013   int NumHalfLaneElts = NumLaneElts / 2;
13014 
13015   bool MatchLo = true, MatchHi = true;
13016   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
13017 
13018   // Determine UNPCKL/UNPCKH type and operand order.
13019   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
13020     for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
13021       int M = Mask[Lane + Elt];
13022       if (M < 0)
13023         continue;
13024 
13025       SDValue &Op = Ops[Elt & 1];
13026       if (M < NumElts && (Op.isUndef() || Op == V1))
13027         Op = V1;
13028       else if (NumElts <= M && (Op.isUndef() || Op == V2))
13029         Op = V2;
13030       else
13031         return SDValue();
13032 
13033       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
13034       MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
13035                  isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
13036       MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
13037                  isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
13038       if (!MatchLo && !MatchHi)
13039         return SDValue();
13040     }
13041   }
13042   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
13043 
13044   // Now check that each pair of elts come from the same unpack pair
13045   // and set the permute mask based on each pair.
13046   // TODO - Investigate cases where we permute individual elements.
13047   SmallVector<int, 32> PermuteMask(NumElts, -1);
13048   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
13049     for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
13050       int M0 = Mask[Lane + Elt + 0];
13051       int M1 = Mask[Lane + Elt + 1];
13052       if (0 <= M0 && 0 <= M1 &&
13053           (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
13054         return SDValue();
13055       if (0 <= M0)
13056         PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
13057       if (0 <= M1)
13058         PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
13059     }
13060   }
13061 
13062   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
13063   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
13064   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
13065 }
13066 
13067 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
13068 /// permuting the elements of the result in place.
13069 static SDValue lowerShuffleAsByteRotateAndPermute(
13070     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13071     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13072   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
13073       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
13074       (VT.is512BitVector() && !Subtarget.hasBWI()))
13075     return SDValue();
13076 
13077   // We don't currently support lane crossing permutes.
13078   if (is128BitLaneCrossingShuffleMask(VT, Mask))
13079     return SDValue();
13080 
13081   int Scale = VT.getScalarSizeInBits() / 8;
13082   int NumLanes = VT.getSizeInBits() / 128;
13083   int NumElts = VT.getVectorNumElements();
13084   int NumEltsPerLane = NumElts / NumLanes;
13085 
13086   // Determine range of mask elts.
13087   bool Blend1 = true;
13088   bool Blend2 = true;
13089   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
13090   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
13091   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
13092     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
13093       int M = Mask[Lane + Elt];
13094       if (M < 0)
13095         continue;
13096       if (M < NumElts) {
13097         Blend1 &= (M == (Lane + Elt));
13098         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
13099         M = M % NumEltsPerLane;
13100         Range1.first = std::min(Range1.first, M);
13101         Range1.second = std::max(Range1.second, M);
13102       } else {
13103         M -= NumElts;
13104         Blend2 &= (M == (Lane + Elt));
13105         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
13106         M = M % NumEltsPerLane;
13107         Range2.first = std::min(Range2.first, M);
13108         Range2.second = std::max(Range2.second, M);
13109       }
13110     }
13111   }
13112 
13113   // Bail if we don't need both elements.
13114   // TODO - it might be worth doing this for unary shuffles if the permute
13115   // can be widened.
13116   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
13117       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
13118     return SDValue();
13119 
13120   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
13121     return SDValue();
13122 
13123   // Rotate the 2 ops so we can access both ranges, then permute the result.
13124   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
13125     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
13126     SDValue Rotate = DAG.getBitcast(
13127         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
13128                         DAG.getBitcast(ByteVT, Lo),
13129                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
13130     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
13131     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
13132       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
13133         int M = Mask[Lane + Elt];
13134         if (M < 0)
13135           continue;
13136         if (M < NumElts)
13137           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
13138         else
13139           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
13140       }
13141     }
13142     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
13143   };
13144 
13145   // Check if the ranges are small enough to rotate from either direction.
13146   if (Range2.second < Range1.first)
13147     return RotateAndPermute(V1, V2, Range1.first, 0);
13148   if (Range1.second < Range2.first)
13149     return RotateAndPermute(V2, V1, Range2.first, NumElts);
13150   return SDValue();
13151 }
13152 
13153 static bool isBroadcastShuffleMask(ArrayRef<int> Mask) {
13154   return isUndefOrEqual(Mask, 0);
13155 }
13156 
13157 static bool isNoopOrBroadcastShuffleMask(ArrayRef<int> Mask) {
13158   return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
13159 }
13160 
13161 /// Generic routine to decompose a shuffle and blend into independent
13162 /// blends and permutes.
13163 ///
13164 /// This matches the extremely common pattern for handling combined
13165 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
13166 /// operations. It will try to pick the best arrangement of shuffles and
13167 /// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
13168 static SDValue lowerShuffleAsDecomposedShuffleMerge(
13169     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13170     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13171   int NumElts = Mask.size();
13172   int NumLanes = VT.getSizeInBits() / 128;
13173   int NumEltsPerLane = NumElts / NumLanes;
13174 
13175   // Shuffle the input elements into the desired positions in V1 and V2 and
13176   // unpack/blend them together.
13177   bool IsAlternating = true;
13178   SmallVector<int, 32> V1Mask(NumElts, -1);
13179   SmallVector<int, 32> V2Mask(NumElts, -1);
13180   SmallVector<int, 32> FinalMask(NumElts, -1);
13181   for (int i = 0; i < NumElts; ++i) {
13182     int M = Mask[i];
13183     if (M >= 0 && M < NumElts) {
13184       V1Mask[i] = M;
13185       FinalMask[i] = i;
13186       IsAlternating &= (i & 1) == 0;
13187     } else if (M >= NumElts) {
13188       V2Mask[i] = M - NumElts;
13189       FinalMask[i] = i + NumElts;
13190       IsAlternating &= (i & 1) == 1;
13191     }
13192   }
13193 
13194   // If we effectively only demand the 0'th element of \p Input, and not only
13195   // as 0'th element, then broadcast said input,
13196   // and change \p InputMask to be a no-op (identity) mask.
13197   auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
13198                                          &DAG](SDValue &Input,
13199                                                MutableArrayRef<int> InputMask) {
13200     unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
13201     if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
13202                                  !X86::mayFoldLoad(Input, Subtarget)))
13203       return;
13204     if (isNoopShuffleMask(InputMask))
13205       return;
13206     assert(isBroadcastShuffleMask(InputMask) &&
13207            "Expected to demand only the 0'th element.");
13208     Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
13209     for (auto I : enumerate(InputMask)) {
13210       int &InputMaskElt = I.value();
13211       if (InputMaskElt >= 0)
13212         InputMaskElt = I.index();
13213     }
13214   };
13215 
13216   // Currently, we may need to produce one shuffle per input, and blend results.
13217   // It is possible that the shuffle for one of the inputs is already a no-op.
13218   // See if we can simplify non-no-op shuffles into broadcasts,
13219   // which we consider to be strictly better than an arbitrary shuffle.
13220   if (isNoopOrBroadcastShuffleMask(V1Mask) &&
13221       isNoopOrBroadcastShuffleMask(V2Mask)) {
13222     canonicalizeBroadcastableInput(V1, V1Mask);
13223     canonicalizeBroadcastableInput(V2, V2Mask);
13224   }
13225 
13226   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
13227   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
13228   // the shuffle may be able to fold with a load or other benefit. However, when
13229   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
13230   // pre-shuffle first is a better strategy.
13231   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
13232     // Only prefer immediate blends to unpack/rotate.
13233     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
13234                                                           DAG, true))
13235       return BlendPerm;
13236     if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
13237                                                            DAG))
13238       return UnpackPerm;
13239     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
13240             DL, VT, V1, V2, Mask, Subtarget, DAG))
13241       return RotatePerm;
13242     // Unpack/rotate failed - try again with variable blends.
13243     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
13244                                                           DAG))
13245       return BlendPerm;
13246   }
13247 
13248   // If the final mask is an alternating blend of vXi8/vXi16, convert to an
13249   // UNPCKL(SHUFFLE, SHUFFLE) pattern.
13250   // TODO: It doesn't have to be alternating - but each lane mustn't have more
13251   // than half the elements coming from each source.
13252   if (IsAlternating && VT.getScalarSizeInBits() < 32) {
13253     V1Mask.assign(NumElts, -1);
13254     V2Mask.assign(NumElts, -1);
13255     FinalMask.assign(NumElts, -1);
13256     for (int i = 0; i != NumElts; i += NumEltsPerLane)
13257       for (int j = 0; j != NumEltsPerLane; ++j) {
13258         int M = Mask[i + j];
13259         if (M >= 0 && M < NumElts) {
13260           V1Mask[i + (j / 2)] = M;
13261           FinalMask[i + j] = i + (j / 2);
13262         } else if (M >= NumElts) {
13263           V2Mask[i + (j / 2)] = M - NumElts;
13264           FinalMask[i + j] = i + (j / 2) + NumElts;
13265         }
13266       }
13267   }
13268 
13269   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
13270   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
13271   return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
13272 }
13273 
13274 /// Try to lower a vector shuffle as a bit rotation.
13275 ///
13276 /// Look for a repeated rotation pattern in each sub group.
13277 /// Returns a ISD::ROTL element rotation amount or -1 if failed.
13278 static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
13279   int NumElts = Mask.size();
13280   assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
13281 
13282   int RotateAmt = -1;
13283   for (int i = 0; i != NumElts; i += NumSubElts) {
13284     for (int j = 0; j != NumSubElts; ++j) {
13285       int M = Mask[i + j];
13286       if (M < 0)
13287         continue;
13288       if (!isInRange(M, i, i + NumSubElts))
13289         return -1;
13290       int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
13291       if (0 <= RotateAmt && Offset != RotateAmt)
13292         return -1;
13293       RotateAmt = Offset;
13294     }
13295   }
13296   return RotateAmt;
13297 }
13298 
13299 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
13300                                    const X86Subtarget &Subtarget,
13301                                    ArrayRef<int> Mask) {
13302   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
13303   assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
13304 
13305   // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
13306   int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
13307   int MaxSubElts = 64 / EltSizeInBits;
13308   for (int NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
13309     int RotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
13310     if (RotateAmt < 0)
13311       continue;
13312 
13313     int NumElts = Mask.size();
13314     MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
13315     RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
13316     return RotateAmt * EltSizeInBits;
13317   }
13318 
13319   return -1;
13320 }
13321 
13322 /// Lower shuffle using X86ISD::VROTLI rotations.
13323 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
13324                                        ArrayRef<int> Mask,
13325                                        const X86Subtarget &Subtarget,
13326                                        SelectionDAG &DAG) {
13327   // Only XOP + AVX512 targets have bit rotation instructions.
13328   // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
13329   bool IsLegal =
13330       (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
13331   if (!IsLegal && Subtarget.hasSSE3())
13332     return SDValue();
13333 
13334   MVT RotateVT;
13335   int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
13336                                           Subtarget, Mask);
13337   if (RotateAmt < 0)
13338     return SDValue();
13339 
13340   // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
13341   // expanded to OR(SRL,SHL), will be more efficient, but if they can
13342   // widen to vXi16 or more then existing lowering should will be better.
13343   if (!IsLegal) {
13344     if ((RotateAmt % 16) == 0)
13345       return SDValue();
13346     // TODO: Use getTargetVShiftByConstNode.
13347     unsigned ShlAmt = RotateAmt;
13348     unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
13349     V1 = DAG.getBitcast(RotateVT, V1);
13350     SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
13351                               DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
13352     SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
13353                               DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
13354     SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
13355     return DAG.getBitcast(VT, Rot);
13356   }
13357 
13358   SDValue Rot =
13359       DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
13360                   DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
13361   return DAG.getBitcast(VT, Rot);
13362 }
13363 
13364 /// Try to match a vector shuffle as an element rotation.
13365 ///
13366 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
13367 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
13368                                        ArrayRef<int> Mask) {
13369   int NumElts = Mask.size();
13370 
13371   // We need to detect various ways of spelling a rotation:
13372   //   [11, 12, 13, 14, 15,  0,  1,  2]
13373   //   [-1, 12, 13, 14, -1, -1,  1, -1]
13374   //   [-1, -1, -1, -1, -1, -1,  1,  2]
13375   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
13376   //   [-1,  4,  5,  6, -1, -1,  9, -1]
13377   //   [-1,  4,  5,  6, -1, -1, -1, -1]
13378   int Rotation = 0;
13379   SDValue Lo, Hi;
13380   for (int i = 0; i < NumElts; ++i) {
13381     int M = Mask[i];
13382     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
13383            "Unexpected mask index.");
13384     if (M < 0)
13385       continue;
13386 
13387     // Determine where a rotated vector would have started.
13388     int StartIdx = i - (M % NumElts);
13389     if (StartIdx == 0)
13390       // The identity rotation isn't interesting, stop.
13391       return -1;
13392 
13393     // If we found the tail of a vector the rotation must be the missing
13394     // front. If we found the head of a vector, it must be how much of the
13395     // head.
13396     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
13397 
13398     if (Rotation == 0)
13399       Rotation = CandidateRotation;
13400     else if (Rotation != CandidateRotation)
13401       // The rotations don't match, so we can't match this mask.
13402       return -1;
13403 
13404     // Compute which value this mask is pointing at.
13405     SDValue MaskV = M < NumElts ? V1 : V2;
13406 
13407     // Compute which of the two target values this index should be assigned
13408     // to. This reflects whether the high elements are remaining or the low
13409     // elements are remaining.
13410     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
13411 
13412     // Either set up this value if we've not encountered it before, or check
13413     // that it remains consistent.
13414     if (!TargetV)
13415       TargetV = MaskV;
13416     else if (TargetV != MaskV)
13417       // This may be a rotation, but it pulls from the inputs in some
13418       // unsupported interleaving.
13419       return -1;
13420   }
13421 
13422   // Check that we successfully analyzed the mask, and normalize the results.
13423   assert(Rotation != 0 && "Failed to locate a viable rotation!");
13424   assert((Lo || Hi) && "Failed to find a rotated input vector!");
13425   if (!Lo)
13426     Lo = Hi;
13427   else if (!Hi)
13428     Hi = Lo;
13429 
13430   V1 = Lo;
13431   V2 = Hi;
13432 
13433   return Rotation;
13434 }
13435 
13436 /// Try to lower a vector shuffle as a byte rotation.
13437 ///
13438 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
13439 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
13440 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
13441 /// try to generically lower a vector shuffle through such an pattern. It
13442 /// does not check for the profitability of lowering either as PALIGNR or
13443 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
13444 /// This matches shuffle vectors that look like:
13445 ///
13446 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
13447 ///
13448 /// Essentially it concatenates V1 and V2, shifts right by some number of
13449 /// elements, and takes the low elements as the result. Note that while this is
13450 /// specified as a *right shift* because x86 is little-endian, it is a *left
13451 /// rotate* of the vector lanes.
13452 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
13453                                     ArrayRef<int> Mask) {
13454   // Don't accept any shuffles with zero elements.
13455   if (isAnyZero(Mask))
13456     return -1;
13457 
13458   // PALIGNR works on 128-bit lanes.
13459   SmallVector<int, 16> RepeatedMask;
13460   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
13461     return -1;
13462 
13463   int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
13464   if (Rotation <= 0)
13465     return -1;
13466 
13467   // PALIGNR rotates bytes, so we need to scale the
13468   // rotation based on how many bytes are in the vector lane.
13469   int NumElts = RepeatedMask.size();
13470   int Scale = 16 / NumElts;
13471   return Rotation * Scale;
13472 }
13473 
13474 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
13475                                         SDValue V2, ArrayRef<int> Mask,
13476                                         const X86Subtarget &Subtarget,
13477                                         SelectionDAG &DAG) {
13478   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
13479 
13480   SDValue Lo = V1, Hi = V2;
13481   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
13482   if (ByteRotation <= 0)
13483     return SDValue();
13484 
13485   // Cast the inputs to i8 vector of correct length to match PALIGNR or
13486   // PSLLDQ/PSRLDQ.
13487   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
13488   Lo = DAG.getBitcast(ByteVT, Lo);
13489   Hi = DAG.getBitcast(ByteVT, Hi);
13490 
13491   // SSSE3 targets can use the palignr instruction.
13492   if (Subtarget.hasSSSE3()) {
13493     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
13494            "512-bit PALIGNR requires BWI instructions");
13495     return DAG.getBitcast(
13496         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
13497                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
13498   }
13499 
13500   assert(VT.is128BitVector() &&
13501          "Rotate-based lowering only supports 128-bit lowering!");
13502   assert(Mask.size() <= 16 &&
13503          "Can shuffle at most 16 bytes in a 128-bit vector!");
13504   assert(ByteVT == MVT::v16i8 &&
13505          "SSE2 rotate lowering only needed for v16i8!");
13506 
13507   // Default SSE2 implementation
13508   int LoByteShift = 16 - ByteRotation;
13509   int HiByteShift = ByteRotation;
13510 
13511   SDValue LoShift =
13512       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
13513                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
13514   SDValue HiShift =
13515       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
13516                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
13517   return DAG.getBitcast(VT,
13518                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
13519 }
13520 
13521 /// Try to lower a vector shuffle as a dword/qword rotation.
13522 ///
13523 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
13524 /// rotation of the concatenation of two vectors; This routine will
13525 /// try to generically lower a vector shuffle through such an pattern.
13526 ///
13527 /// Essentially it concatenates V1 and V2, shifts right by some number of
13528 /// elements, and takes the low elements as the result. Note that while this is
13529 /// specified as a *right shift* because x86 is little-endian, it is a *left
13530 /// rotate* of the vector lanes.
13531 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
13532                                     SDValue V2, ArrayRef<int> Mask,
13533                                     const X86Subtarget &Subtarget,
13534                                     SelectionDAG &DAG) {
13535   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
13536          "Only 32-bit and 64-bit elements are supported!");
13537 
13538   // 128/256-bit vectors are only supported with VLX.
13539   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
13540          && "VLX required for 128/256-bit vectors");
13541 
13542   SDValue Lo = V1, Hi = V2;
13543   int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
13544   if (Rotation <= 0)
13545     return SDValue();
13546 
13547   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
13548                      DAG.getTargetConstant(Rotation, DL, MVT::i8));
13549 }
13550 
13551 /// Try to lower a vector shuffle as a byte shift sequence.
13552 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
13553                                            SDValue V2, ArrayRef<int> Mask,
13554                                            const APInt &Zeroable,
13555                                            const X86Subtarget &Subtarget,
13556                                            SelectionDAG &DAG) {
13557   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
13558   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
13559 
13560   // We need a shuffle that has zeros at one/both ends and a sequential
13561   // shuffle from one source within.
13562   unsigned ZeroLo = Zeroable.countTrailingOnes();
13563   unsigned ZeroHi = Zeroable.countLeadingOnes();
13564   if (!ZeroLo && !ZeroHi)
13565     return SDValue();
13566 
13567   unsigned NumElts = Mask.size();
13568   unsigned Len = NumElts - (ZeroLo + ZeroHi);
13569   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
13570     return SDValue();
13571 
13572   unsigned Scale = VT.getScalarSizeInBits() / 8;
13573   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
13574   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
13575       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
13576     return SDValue();
13577 
13578   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
13579   Res = DAG.getBitcast(MVT::v16i8, Res);
13580 
13581   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
13582   // inner sequential set of elements, possibly offset:
13583   // 01234567 --> zzzzzz01 --> 1zzzzzzz
13584   // 01234567 --> 4567zzzz --> zzzzz456
13585   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
13586   if (ZeroLo == 0) {
13587     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
13588     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13589                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13590     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
13591                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
13592   } else if (ZeroHi == 0) {
13593     unsigned Shift = Mask[ZeroLo] % NumElts;
13594     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
13595                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13596     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13597                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
13598   } else if (!Subtarget.hasSSSE3()) {
13599     // If we don't have PSHUFB then its worth avoiding an AND constant mask
13600     // by performing 3 byte shifts. Shuffle combining can kick in above that.
13601     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
13602     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
13603     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13604                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13605     Shift += Mask[ZeroLo] % NumElts;
13606     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
13607                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13608     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13609                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
13610   } else
13611     return SDValue();
13612 
13613   return DAG.getBitcast(VT, Res);
13614 }
13615 
13616 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
13617 ///
13618 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
13619 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
13620 /// matches elements from one of the input vectors shuffled to the left or
13621 /// right with zeroable elements 'shifted in'. It handles both the strictly
13622 /// bit-wise element shifts and the byte shift across an entire 128-bit double
13623 /// quad word lane.
13624 ///
13625 /// PSHL : (little-endian) left bit shift.
13626 /// [ zz, 0, zz,  2 ]
13627 /// [ -1, 4, zz, -1 ]
13628 /// PSRL : (little-endian) right bit shift.
13629 /// [  1, zz,  3, zz]
13630 /// [ -1, -1,  7, zz]
13631 /// PSLLDQ : (little-endian) left byte shift
13632 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
13633 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
13634 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
13635 /// PSRLDQ : (little-endian) right byte shift
13636 /// [  5, 6,  7, zz, zz, zz, zz, zz]
13637 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
13638 /// [  1, 2, -1, -1, -1, -1, zz, zz]
13639 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
13640                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
13641                                int MaskOffset, const APInt &Zeroable,
13642                                const X86Subtarget &Subtarget) {
13643   int Size = Mask.size();
13644   unsigned SizeInBits = Size * ScalarSizeInBits;
13645 
13646   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
13647     for (int i = 0; i < Size; i += Scale)
13648       for (int j = 0; j < Shift; ++j)
13649         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
13650           return false;
13651 
13652     return true;
13653   };
13654 
13655   auto MatchShift = [&](int Shift, int Scale, bool Left) {
13656     for (int i = 0; i != Size; i += Scale) {
13657       unsigned Pos = Left ? i + Shift : i;
13658       unsigned Low = Left ? i : i + Shift;
13659       unsigned Len = Scale - Shift;
13660       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
13661         return -1;
13662     }
13663 
13664     int ShiftEltBits = ScalarSizeInBits * Scale;
13665     bool ByteShift = ShiftEltBits > 64;
13666     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
13667                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
13668     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
13669 
13670     // Normalize the scale for byte shifts to still produce an i64 element
13671     // type.
13672     Scale = ByteShift ? Scale / 2 : Scale;
13673 
13674     // We need to round trip through the appropriate type for the shift.
13675     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
13676     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
13677                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
13678     return (int)ShiftAmt;
13679   };
13680 
13681   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
13682   // keep doubling the size of the integer elements up to that. We can
13683   // then shift the elements of the integer vector by whole multiples of
13684   // their width within the elements of the larger integer vector. Test each
13685   // multiple to see if we can find a match with the moved element indices
13686   // and that the shifted in elements are all zeroable.
13687   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
13688   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
13689     for (int Shift = 1; Shift != Scale; ++Shift)
13690       for (bool Left : {true, false})
13691         if (CheckZeros(Shift, Scale, Left)) {
13692           int ShiftAmt = MatchShift(Shift, Scale, Left);
13693           if (0 < ShiftAmt)
13694             return ShiftAmt;
13695         }
13696 
13697   // no match
13698   return -1;
13699 }
13700 
13701 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
13702                                    SDValue V2, ArrayRef<int> Mask,
13703                                    const APInt &Zeroable,
13704                                    const X86Subtarget &Subtarget,
13705                                    SelectionDAG &DAG) {
13706   int Size = Mask.size();
13707   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
13708 
13709   MVT ShiftVT;
13710   SDValue V = V1;
13711   unsigned Opcode;
13712 
13713   // Try to match shuffle against V1 shift.
13714   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
13715                                      Mask, 0, Zeroable, Subtarget);
13716 
13717   // If V1 failed, try to match shuffle against V2 shift.
13718   if (ShiftAmt < 0) {
13719     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
13720                                    Mask, Size, Zeroable, Subtarget);
13721     V = V2;
13722   }
13723 
13724   if (ShiftAmt < 0)
13725     return SDValue();
13726 
13727   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
13728          "Illegal integer vector type");
13729   V = DAG.getBitcast(ShiftVT, V);
13730   V = DAG.getNode(Opcode, DL, ShiftVT, V,
13731                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
13732   return DAG.getBitcast(VT, V);
13733 }
13734 
13735 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
13736 // Remainder of lower half result is zero and upper half is all undef.
13737 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
13738                                 ArrayRef<int> Mask, uint64_t &BitLen,
13739                                 uint64_t &BitIdx, const APInt &Zeroable) {
13740   int Size = Mask.size();
13741   int HalfSize = Size / 2;
13742   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
13743   assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
13744 
13745   // Upper half must be undefined.
13746   if (!isUndefUpperHalf(Mask))
13747     return false;
13748 
13749   // Determine the extraction length from the part of the
13750   // lower half that isn't zeroable.
13751   int Len = HalfSize;
13752   for (; Len > 0; --Len)
13753     if (!Zeroable[Len - 1])
13754       break;
13755   assert(Len > 0 && "Zeroable shuffle mask");
13756 
13757   // Attempt to match first Len sequential elements from the lower half.
13758   SDValue Src;
13759   int Idx = -1;
13760   for (int i = 0; i != Len; ++i) {
13761     int M = Mask[i];
13762     if (M == SM_SentinelUndef)
13763       continue;
13764     SDValue &V = (M < Size ? V1 : V2);
13765     M = M % Size;
13766 
13767     // The extracted elements must start at a valid index and all mask
13768     // elements must be in the lower half.
13769     if (i > M || M >= HalfSize)
13770       return false;
13771 
13772     if (Idx < 0 || (Src == V && Idx == (M - i))) {
13773       Src = V;
13774       Idx = M - i;
13775       continue;
13776     }
13777     return false;
13778   }
13779 
13780   if (!Src || Idx < 0)
13781     return false;
13782 
13783   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
13784   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
13785   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
13786   V1 = Src;
13787   return true;
13788 }
13789 
13790 // INSERTQ: Extract lowest Len elements from lower half of second source and
13791 // insert over first source, starting at Idx.
13792 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
13793 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
13794                                   ArrayRef<int> Mask, uint64_t &BitLen,
13795                                   uint64_t &BitIdx) {
13796   int Size = Mask.size();
13797   int HalfSize = Size / 2;
13798   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
13799 
13800   // Upper half must be undefined.
13801   if (!isUndefUpperHalf(Mask))
13802     return false;
13803 
13804   for (int Idx = 0; Idx != HalfSize; ++Idx) {
13805     SDValue Base;
13806 
13807     // Attempt to match first source from mask before insertion point.
13808     if (isUndefInRange(Mask, 0, Idx)) {
13809       /* EMPTY */
13810     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
13811       Base = V1;
13812     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
13813       Base = V2;
13814     } else {
13815       continue;
13816     }
13817 
13818     // Extend the extraction length looking to match both the insertion of
13819     // the second source and the remaining elements of the first.
13820     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
13821       SDValue Insert;
13822       int Len = Hi - Idx;
13823 
13824       // Match insertion.
13825       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
13826         Insert = V1;
13827       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
13828         Insert = V2;
13829       } else {
13830         continue;
13831       }
13832 
13833       // Match the remaining elements of the lower half.
13834       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
13835         /* EMPTY */
13836       } else if ((!Base || (Base == V1)) &&
13837                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
13838         Base = V1;
13839       } else if ((!Base || (Base == V2)) &&
13840                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
13841                                             Size + Hi)) {
13842         Base = V2;
13843       } else {
13844         continue;
13845       }
13846 
13847       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
13848       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
13849       V1 = Base;
13850       V2 = Insert;
13851       return true;
13852     }
13853   }
13854 
13855   return false;
13856 }
13857 
13858 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
13859 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
13860                                      SDValue V2, ArrayRef<int> Mask,
13861                                      const APInt &Zeroable, SelectionDAG &DAG) {
13862   uint64_t BitLen, BitIdx;
13863   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
13864     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
13865                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
13866                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
13867 
13868   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
13869     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
13870                        V2 ? V2 : DAG.getUNDEF(VT),
13871                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
13872                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
13873 
13874   return SDValue();
13875 }
13876 
13877 /// Lower a vector shuffle as a zero or any extension.
13878 ///
13879 /// Given a specific number of elements, element bit width, and extension
13880 /// stride, produce either a zero or any extension based on the available
13881 /// features of the subtarget. The extended elements are consecutive and
13882 /// begin and can start from an offsetted element index in the input; to
13883 /// avoid excess shuffling the offset must either being in the bottom lane
13884 /// or at the start of a higher lane. All extended elements must be from
13885 /// the same lane.
13886 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
13887     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
13888     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13889   assert(Scale > 1 && "Need a scale to extend.");
13890   int EltBits = VT.getScalarSizeInBits();
13891   int NumElements = VT.getVectorNumElements();
13892   int NumEltsPerLane = 128 / EltBits;
13893   int OffsetLane = Offset / NumEltsPerLane;
13894   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
13895          "Only 8, 16, and 32 bit elements can be extended.");
13896   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
13897   assert(0 <= Offset && "Extension offset must be positive.");
13898   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
13899          "Extension offset must be in the first lane or start an upper lane.");
13900 
13901   // Check that an index is in same lane as the base offset.
13902   auto SafeOffset = [&](int Idx) {
13903     return OffsetLane == (Idx / NumEltsPerLane);
13904   };
13905 
13906   // Shift along an input so that the offset base moves to the first element.
13907   auto ShuffleOffset = [&](SDValue V) {
13908     if (!Offset)
13909       return V;
13910 
13911     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13912     for (int i = 0; i * Scale < NumElements; ++i) {
13913       int SrcIdx = i + Offset;
13914       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
13915     }
13916     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
13917   };
13918 
13919   // Found a valid a/zext mask! Try various lowering strategies based on the
13920   // input type and available ISA extensions.
13921   if (Subtarget.hasSSE41()) {
13922     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
13923     // PUNPCK will catch this in a later shuffle match.
13924     if (Offset && Scale == 2 && VT.is128BitVector())
13925       return SDValue();
13926     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
13927                                  NumElements / Scale);
13928     InputV = ShuffleOffset(InputV);
13929     InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
13930                                     DL, ExtVT, InputV, DAG);
13931     return DAG.getBitcast(VT, InputV);
13932   }
13933 
13934   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
13935 
13936   // For any extends we can cheat for larger element sizes and use shuffle
13937   // instructions that can fold with a load and/or copy.
13938   if (AnyExt && EltBits == 32) {
13939     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
13940                          -1};
13941     return DAG.getBitcast(
13942         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13943                         DAG.getBitcast(MVT::v4i32, InputV),
13944                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13945   }
13946   if (AnyExt && EltBits == 16 && Scale > 2) {
13947     int PSHUFDMask[4] = {Offset / 2, -1,
13948                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
13949     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13950                          DAG.getBitcast(MVT::v4i32, InputV),
13951                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13952     int PSHUFWMask[4] = {1, -1, -1, -1};
13953     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
13954     return DAG.getBitcast(
13955         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
13956                         DAG.getBitcast(MVT::v8i16, InputV),
13957                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
13958   }
13959 
13960   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
13961   // to 64-bits.
13962   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
13963     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
13964     assert(VT.is128BitVector() && "Unexpected vector width!");
13965 
13966     int LoIdx = Offset * EltBits;
13967     SDValue Lo = DAG.getBitcast(
13968         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13969                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13970                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
13971 
13972     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
13973       return DAG.getBitcast(VT, Lo);
13974 
13975     int HiIdx = (Offset + 1) * EltBits;
13976     SDValue Hi = DAG.getBitcast(
13977         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13978                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13979                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
13980     return DAG.getBitcast(VT,
13981                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
13982   }
13983 
13984   // If this would require more than 2 unpack instructions to expand, use
13985   // pshufb when available. We can only use more than 2 unpack instructions
13986   // when zero extending i8 elements which also makes it easier to use pshufb.
13987   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
13988     assert(NumElements == 16 && "Unexpected byte vector width!");
13989     SDValue PSHUFBMask[16];
13990     for (int i = 0; i < 16; ++i) {
13991       int Idx = Offset + (i / Scale);
13992       if ((i % Scale == 0 && SafeOffset(Idx))) {
13993         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
13994         continue;
13995       }
13996       PSHUFBMask[i] =
13997           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
13998     }
13999     InputV = DAG.getBitcast(MVT::v16i8, InputV);
14000     return DAG.getBitcast(
14001         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
14002                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
14003   }
14004 
14005   // If we are extending from an offset, ensure we start on a boundary that
14006   // we can unpack from.
14007   int AlignToUnpack = Offset % (NumElements / Scale);
14008   if (AlignToUnpack) {
14009     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
14010     for (int i = AlignToUnpack; i < NumElements; ++i)
14011       ShMask[i - AlignToUnpack] = i;
14012     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
14013     Offset -= AlignToUnpack;
14014   }
14015 
14016   // Otherwise emit a sequence of unpacks.
14017   do {
14018     unsigned UnpackLoHi = X86ISD::UNPCKL;
14019     if (Offset >= (NumElements / 2)) {
14020       UnpackLoHi = X86ISD::UNPCKH;
14021       Offset -= (NumElements / 2);
14022     }
14023 
14024     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
14025     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
14026                          : getZeroVector(InputVT, Subtarget, DAG, DL);
14027     InputV = DAG.getBitcast(InputVT, InputV);
14028     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
14029     Scale /= 2;
14030     EltBits *= 2;
14031     NumElements /= 2;
14032   } while (Scale > 1);
14033   return DAG.getBitcast(VT, InputV);
14034 }
14035 
14036 /// Try to lower a vector shuffle as a zero extension on any microarch.
14037 ///
14038 /// This routine will try to do everything in its power to cleverly lower
14039 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
14040 /// check for the profitability of this lowering,  it tries to aggressively
14041 /// match this pattern. It will use all of the micro-architectural details it
14042 /// can to emit an efficient lowering. It handles both blends with all-zero
14043 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
14044 /// masking out later).
14045 ///
14046 /// The reason we have dedicated lowering for zext-style shuffles is that they
14047 /// are both incredibly common and often quite performance sensitive.
14048 static SDValue lowerShuffleAsZeroOrAnyExtend(
14049     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14050     const APInt &Zeroable, const X86Subtarget &Subtarget,
14051     SelectionDAG &DAG) {
14052   int Bits = VT.getSizeInBits();
14053   int NumLanes = Bits / 128;
14054   int NumElements = VT.getVectorNumElements();
14055   int NumEltsPerLane = NumElements / NumLanes;
14056   assert(VT.getScalarSizeInBits() <= 32 &&
14057          "Exceeds 32-bit integer zero extension limit");
14058   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
14059 
14060   // Define a helper function to check a particular ext-scale and lower to it if
14061   // valid.
14062   auto Lower = [&](int Scale) -> SDValue {
14063     SDValue InputV;
14064     bool AnyExt = true;
14065     int Offset = 0;
14066     int Matches = 0;
14067     for (int i = 0; i < NumElements; ++i) {
14068       int M = Mask[i];
14069       if (M < 0)
14070         continue; // Valid anywhere but doesn't tell us anything.
14071       if (i % Scale != 0) {
14072         // Each of the extended elements need to be zeroable.
14073         if (!Zeroable[i])
14074           return SDValue();
14075 
14076         // We no longer are in the anyext case.
14077         AnyExt = false;
14078         continue;
14079       }
14080 
14081       // Each of the base elements needs to be consecutive indices into the
14082       // same input vector.
14083       SDValue V = M < NumElements ? V1 : V2;
14084       M = M % NumElements;
14085       if (!InputV) {
14086         InputV = V;
14087         Offset = M - (i / Scale);
14088       } else if (InputV != V)
14089         return SDValue(); // Flip-flopping inputs.
14090 
14091       // Offset must start in the lowest 128-bit lane or at the start of an
14092       // upper lane.
14093       // FIXME: Is it ever worth allowing a negative base offset?
14094       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
14095             (Offset % NumEltsPerLane) == 0))
14096         return SDValue();
14097 
14098       // If we are offsetting, all referenced entries must come from the same
14099       // lane.
14100       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
14101         return SDValue();
14102 
14103       if ((M % NumElements) != (Offset + (i / Scale)))
14104         return SDValue(); // Non-consecutive strided elements.
14105       Matches++;
14106     }
14107 
14108     // If we fail to find an input, we have a zero-shuffle which should always
14109     // have already been handled.
14110     // FIXME: Maybe handle this here in case during blending we end up with one?
14111     if (!InputV)
14112       return SDValue();
14113 
14114     // If we are offsetting, don't extend if we only match a single input, we
14115     // can always do better by using a basic PSHUF or PUNPCK.
14116     if (Offset != 0 && Matches < 2)
14117       return SDValue();
14118 
14119     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
14120                                                  InputV, Mask, Subtarget, DAG);
14121   };
14122 
14123   // The widest scale possible for extending is to a 64-bit integer.
14124   assert(Bits % 64 == 0 &&
14125          "The number of bits in a vector must be divisible by 64 on x86!");
14126   int NumExtElements = Bits / 64;
14127 
14128   // Each iteration, try extending the elements half as much, but into twice as
14129   // many elements.
14130   for (; NumExtElements < NumElements; NumExtElements *= 2) {
14131     assert(NumElements % NumExtElements == 0 &&
14132            "The input vector size must be divisible by the extended size.");
14133     if (SDValue V = Lower(NumElements / NumExtElements))
14134       return V;
14135   }
14136 
14137   // General extends failed, but 128-bit vectors may be able to use MOVQ.
14138   if (Bits != 128)
14139     return SDValue();
14140 
14141   // Returns one of the source operands if the shuffle can be reduced to a
14142   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
14143   auto CanZExtLowHalf = [&]() {
14144     for (int i = NumElements / 2; i != NumElements; ++i)
14145       if (!Zeroable[i])
14146         return SDValue();
14147     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
14148       return V1;
14149     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
14150       return V2;
14151     return SDValue();
14152   };
14153 
14154   if (SDValue V = CanZExtLowHalf()) {
14155     V = DAG.getBitcast(MVT::v2i64, V);
14156     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
14157     return DAG.getBitcast(VT, V);
14158   }
14159 
14160   // No viable ext lowering found.
14161   return SDValue();
14162 }
14163 
14164 /// Try to get a scalar value for a specific element of a vector.
14165 ///
14166 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
14167 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
14168                                               SelectionDAG &DAG) {
14169   MVT VT = V.getSimpleValueType();
14170   MVT EltVT = VT.getVectorElementType();
14171   V = peekThroughBitcasts(V);
14172 
14173   // If the bitcasts shift the element size, we can't extract an equivalent
14174   // element from it.
14175   MVT NewVT = V.getSimpleValueType();
14176   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
14177     return SDValue();
14178 
14179   if (V.getOpcode() == ISD::BUILD_VECTOR ||
14180       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
14181     // Ensure the scalar operand is the same size as the destination.
14182     // FIXME: Add support for scalar truncation where possible.
14183     SDValue S = V.getOperand(Idx);
14184     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
14185       return DAG.getBitcast(EltVT, S);
14186   }
14187 
14188   return SDValue();
14189 }
14190 
14191 /// Helper to test for a load that can be folded with x86 shuffles.
14192 ///
14193 /// This is particularly important because the set of instructions varies
14194 /// significantly based on whether the operand is a load or not.
14195 static bool isShuffleFoldableLoad(SDValue V) {
14196   return V->hasOneUse() &&
14197          ISD::isNON_EXTLoad(peekThroughOneUseBitcasts(V).getNode());
14198 }
14199 
14200 template<typename T>
14201 static bool isSoftFP16(T VT, const X86Subtarget &Subtarget) {
14202   return VT.getScalarType() == MVT::f16 && !Subtarget.hasFP16();
14203 }
14204 
14205 template<typename T>
14206 bool X86TargetLowering::isSoftFP16(T VT) const {
14207   return ::isSoftFP16(VT, Subtarget);
14208 }
14209 
14210 /// Try to lower insertion of a single element into a zero vector.
14211 ///
14212 /// This is a common pattern that we have especially efficient patterns to lower
14213 /// across all subtarget feature sets.
14214 static SDValue lowerShuffleAsElementInsertion(
14215     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14216     const APInt &Zeroable, const X86Subtarget &Subtarget,
14217     SelectionDAG &DAG) {
14218   MVT ExtVT = VT;
14219   MVT EltVT = VT.getVectorElementType();
14220 
14221   if (isSoftFP16(EltVT, Subtarget))
14222     return SDValue();
14223 
14224   int V2Index =
14225       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
14226       Mask.begin();
14227   bool IsV1Zeroable = true;
14228   for (int i = 0, Size = Mask.size(); i < Size; ++i)
14229     if (i != V2Index && !Zeroable[i]) {
14230       IsV1Zeroable = false;
14231       break;
14232     }
14233 
14234   // Check for a single input from a SCALAR_TO_VECTOR node.
14235   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
14236   // all the smarts here sunk into that routine. However, the current
14237   // lowering of BUILD_VECTOR makes that nearly impossible until the old
14238   // vector shuffle lowering is dead.
14239   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
14240                                                DAG);
14241   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
14242     // We need to zext the scalar if it is smaller than an i32.
14243     V2S = DAG.getBitcast(EltVT, V2S);
14244     if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
14245       // Using zext to expand a narrow element won't work for non-zero
14246       // insertions.
14247       if (!IsV1Zeroable)
14248         return SDValue();
14249 
14250       // Zero-extend directly to i32.
14251       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
14252       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
14253     }
14254     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
14255   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
14256              EltVT == MVT::i16) {
14257     // Either not inserting from the low element of the input or the input
14258     // element size is too small to use VZEXT_MOVL to clear the high bits.
14259     return SDValue();
14260   }
14261 
14262   if (!IsV1Zeroable) {
14263     // If V1 can't be treated as a zero vector we have fewer options to lower
14264     // this. We can't support integer vectors or non-zero targets cheaply, and
14265     // the V1 elements can't be permuted in any way.
14266     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
14267     if (!VT.isFloatingPoint() || V2Index != 0)
14268       return SDValue();
14269     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
14270     V1Mask[V2Index] = -1;
14271     if (!isNoopShuffleMask(V1Mask))
14272       return SDValue();
14273     if (!VT.is128BitVector())
14274       return SDValue();
14275 
14276     // Otherwise, use MOVSD, MOVSS or MOVSH.
14277     unsigned MovOpc = 0;
14278     if (EltVT == MVT::f16)
14279       MovOpc = X86ISD::MOVSH;
14280     else if (EltVT == MVT::f32)
14281       MovOpc = X86ISD::MOVSS;
14282     else if (EltVT == MVT::f64)
14283       MovOpc = X86ISD::MOVSD;
14284     else
14285       llvm_unreachable("Unsupported floating point element type to handle!");
14286     return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
14287   }
14288 
14289   // This lowering only works for the low element with floating point vectors.
14290   if (VT.isFloatingPoint() && V2Index != 0)
14291     return SDValue();
14292 
14293   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
14294   if (ExtVT != VT)
14295     V2 = DAG.getBitcast(VT, V2);
14296 
14297   if (V2Index != 0) {
14298     // If we have 4 or fewer lanes we can cheaply shuffle the element into
14299     // the desired position. Otherwise it is more efficient to do a vector
14300     // shift left. We know that we can do a vector shift left because all
14301     // the inputs are zero.
14302     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
14303       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
14304       V2Shuffle[V2Index] = 0;
14305       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
14306     } else {
14307       V2 = DAG.getBitcast(MVT::v16i8, V2);
14308       V2 = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
14309                        DAG.getTargetConstant(
14310                            V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
14311       V2 = DAG.getBitcast(VT, V2);
14312     }
14313   }
14314   return V2;
14315 }
14316 
14317 /// Try to lower broadcast of a single - truncated - integer element,
14318 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
14319 ///
14320 /// This assumes we have AVX2.
14321 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
14322                                             int BroadcastIdx,
14323                                             const X86Subtarget &Subtarget,
14324                                             SelectionDAG &DAG) {
14325   assert(Subtarget.hasAVX2() &&
14326          "We can only lower integer broadcasts with AVX2!");
14327 
14328   MVT EltVT = VT.getVectorElementType();
14329   MVT V0VT = V0.getSimpleValueType();
14330 
14331   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
14332   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
14333 
14334   MVT V0EltVT = V0VT.getVectorElementType();
14335   if (!V0EltVT.isInteger())
14336     return SDValue();
14337 
14338   const unsigned EltSize = EltVT.getSizeInBits();
14339   const unsigned V0EltSize = V0EltVT.getSizeInBits();
14340 
14341   // This is only a truncation if the original element type is larger.
14342   if (V0EltSize <= EltSize)
14343     return SDValue();
14344 
14345   assert(((V0EltSize % EltSize) == 0) &&
14346          "Scalar type sizes must all be powers of 2 on x86!");
14347 
14348   const unsigned V0Opc = V0.getOpcode();
14349   const unsigned Scale = V0EltSize / EltSize;
14350   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
14351 
14352   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
14353       V0Opc != ISD::BUILD_VECTOR)
14354     return SDValue();
14355 
14356   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
14357 
14358   // If we're extracting non-least-significant bits, shift so we can truncate.
14359   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
14360   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
14361   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
14362   if (const int OffsetIdx = BroadcastIdx % Scale)
14363     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
14364                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
14365 
14366   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
14367                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
14368 }
14369 
14370 /// Test whether this can be lowered with a single SHUFPS instruction.
14371 ///
14372 /// This is used to disable more specialized lowerings when the shufps lowering
14373 /// will happen to be efficient.
14374 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
14375   // This routine only handles 128-bit shufps.
14376   assert(Mask.size() == 4 && "Unsupported mask size!");
14377   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
14378   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
14379   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
14380   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
14381 
14382   // To lower with a single SHUFPS we need to have the low half and high half
14383   // each requiring a single input.
14384   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
14385     return false;
14386   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
14387     return false;
14388 
14389   return true;
14390 }
14391 
14392 /// If we are extracting two 128-bit halves of a vector and shuffling the
14393 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
14394 /// multi-shuffle lowering.
14395 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
14396                                              SDValue N1, ArrayRef<int> Mask,
14397                                              SelectionDAG &DAG) {
14398   MVT VT = N0.getSimpleValueType();
14399   assert((VT.is128BitVector() &&
14400           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
14401          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
14402 
14403   // Check that both sources are extracts of the same source vector.
14404   if (!N0.hasOneUse() || !N1.hasOneUse() ||
14405       N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14406       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14407       N0.getOperand(0) != N1.getOperand(0))
14408     return SDValue();
14409 
14410   SDValue WideVec = N0.getOperand(0);
14411   MVT WideVT = WideVec.getSimpleValueType();
14412   if (!WideVT.is256BitVector())
14413     return SDValue();
14414 
14415   // Match extracts of each half of the wide source vector. Commute the shuffle
14416   // if the extract of the low half is N1.
14417   unsigned NumElts = VT.getVectorNumElements();
14418   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
14419   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
14420   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
14421   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
14422     ShuffleVectorSDNode::commuteMask(NewMask);
14423   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
14424     return SDValue();
14425 
14426   // Final bailout: if the mask is simple, we are better off using an extract
14427   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
14428   // because that avoids a constant load from memory.
14429   if (NumElts == 4 &&
14430       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
14431     return SDValue();
14432 
14433   // Extend the shuffle mask with undef elements.
14434   NewMask.append(NumElts, -1);
14435 
14436   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
14437   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
14438                                       NewMask);
14439   // This is free: ymm -> xmm.
14440   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
14441                      DAG.getIntPtrConstant(0, DL));
14442 }
14443 
14444 /// Try to lower broadcast of a single element.
14445 ///
14446 /// For convenience, this code also bundles all of the subtarget feature set
14447 /// filtering. While a little annoying to re-dispatch on type here, there isn't
14448 /// a convenient way to factor it out.
14449 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
14450                                        SDValue V2, ArrayRef<int> Mask,
14451                                        const X86Subtarget &Subtarget,
14452                                        SelectionDAG &DAG) {
14453   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
14454         (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
14455         (Subtarget.hasAVX2() && VT.isInteger())))
14456     return SDValue();
14457 
14458   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
14459   // we can only broadcast from a register with AVX2.
14460   unsigned NumEltBits = VT.getScalarSizeInBits();
14461   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
14462                         ? X86ISD::MOVDDUP
14463                         : X86ISD::VBROADCAST;
14464   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
14465 
14466   // Check that the mask is a broadcast.
14467   int BroadcastIdx = getSplatIndex(Mask);
14468   if (BroadcastIdx < 0)
14469     return SDValue();
14470   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
14471                                             "a sorted mask where the broadcast "
14472                                             "comes from V1.");
14473 
14474   // Go up the chain of (vector) values to find a scalar load that we can
14475   // combine with the broadcast.
14476   // TODO: Combine this logic with findEltLoadSrc() used by
14477   //       EltsFromConsecutiveLoads().
14478   int BitOffset = BroadcastIdx * NumEltBits;
14479   SDValue V = V1;
14480   for (;;) {
14481     switch (V.getOpcode()) {
14482     case ISD::BITCAST: {
14483       V = V.getOperand(0);
14484       continue;
14485     }
14486     case ISD::CONCAT_VECTORS: {
14487       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
14488       int OpIdx = BitOffset / OpBitWidth;
14489       V = V.getOperand(OpIdx);
14490       BitOffset %= OpBitWidth;
14491       continue;
14492     }
14493     case ISD::EXTRACT_SUBVECTOR: {
14494       // The extraction index adds to the existing offset.
14495       unsigned EltBitWidth = V.getScalarValueSizeInBits();
14496       unsigned Idx = V.getConstantOperandVal(1);
14497       unsigned BeginOffset = Idx * EltBitWidth;
14498       BitOffset += BeginOffset;
14499       V = V.getOperand(0);
14500       continue;
14501     }
14502     case ISD::INSERT_SUBVECTOR: {
14503       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
14504       int EltBitWidth = VOuter.getScalarValueSizeInBits();
14505       int Idx = (int)V.getConstantOperandVal(2);
14506       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
14507       int BeginOffset = Idx * EltBitWidth;
14508       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
14509       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
14510         BitOffset -= BeginOffset;
14511         V = VInner;
14512       } else {
14513         V = VOuter;
14514       }
14515       continue;
14516     }
14517     }
14518     break;
14519   }
14520   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
14521   BroadcastIdx = BitOffset / NumEltBits;
14522 
14523   // Do we need to bitcast the source to retrieve the original broadcast index?
14524   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
14525 
14526   // Check if this is a broadcast of a scalar. We special case lowering
14527   // for scalars so that we can more effectively fold with loads.
14528   // If the original value has a larger element type than the shuffle, the
14529   // broadcast element is in essence truncated. Make that explicit to ease
14530   // folding.
14531   if (BitCastSrc && VT.isInteger())
14532     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
14533             DL, VT, V, BroadcastIdx, Subtarget, DAG))
14534       return TruncBroadcast;
14535 
14536   // Also check the simpler case, where we can directly reuse the scalar.
14537   if (!BitCastSrc &&
14538       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
14539        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
14540     V = V.getOperand(BroadcastIdx);
14541 
14542     // If we can't broadcast from a register, check that the input is a load.
14543     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
14544       return SDValue();
14545   } else if (ISD::isNormalLoad(V.getNode()) &&
14546              cast<LoadSDNode>(V)->isSimple()) {
14547     // We do not check for one-use of the vector load because a broadcast load
14548     // is expected to be a win for code size, register pressure, and possibly
14549     // uops even if the original vector load is not eliminated.
14550 
14551     // Reduce the vector load and shuffle to a broadcasted scalar load.
14552     LoadSDNode *Ld = cast<LoadSDNode>(V);
14553     SDValue BaseAddr = Ld->getOperand(1);
14554     MVT SVT = VT.getScalarType();
14555     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
14556     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
14557     SDValue NewAddr =
14558         DAG.getMemBasePlusOffset(BaseAddr, TypeSize::Fixed(Offset), DL);
14559 
14560     // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
14561     // than MOVDDUP.
14562     // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
14563     if (Opcode == X86ISD::VBROADCAST) {
14564       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
14565       SDValue Ops[] = {Ld->getChain(), NewAddr};
14566       V = DAG.getMemIntrinsicNode(
14567           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
14568           DAG.getMachineFunction().getMachineMemOperand(
14569               Ld->getMemOperand(), Offset, SVT.getStoreSize()));
14570       DAG.makeEquivalentMemoryOrdering(Ld, V);
14571       return DAG.getBitcast(VT, V);
14572     }
14573     assert(SVT == MVT::f64 && "Unexpected VT!");
14574     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
14575                     DAG.getMachineFunction().getMachineMemOperand(
14576                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
14577     DAG.makeEquivalentMemoryOrdering(Ld, V);
14578   } else if (!BroadcastFromReg) {
14579     // We can't broadcast from a vector register.
14580     return SDValue();
14581   } else if (BitOffset != 0) {
14582     // We can only broadcast from the zero-element of a vector register,
14583     // but it can be advantageous to broadcast from the zero-element of a
14584     // subvector.
14585     if (!VT.is256BitVector() && !VT.is512BitVector())
14586       return SDValue();
14587 
14588     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
14589     if (VT == MVT::v4f64 || VT == MVT::v4i64)
14590       return SDValue();
14591 
14592     // Only broadcast the zero-element of a 128-bit subvector.
14593     if ((BitOffset % 128) != 0)
14594       return SDValue();
14595 
14596     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
14597            "Unexpected bit-offset");
14598     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
14599            "Unexpected vector size");
14600     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
14601     V = extract128BitVector(V, ExtractIdx, DAG, DL);
14602   }
14603 
14604   // On AVX we can use VBROADCAST directly for scalar sources.
14605   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
14606     V = DAG.getBitcast(MVT::f64, V);
14607     if (Subtarget.hasAVX()) {
14608       V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
14609       return DAG.getBitcast(VT, V);
14610     }
14611     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
14612   }
14613 
14614   // If this is a scalar, do the broadcast on this type and bitcast.
14615   if (!V.getValueType().isVector()) {
14616     assert(V.getScalarValueSizeInBits() == NumEltBits &&
14617            "Unexpected scalar size");
14618     MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
14619                                        VT.getVectorNumElements());
14620     return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
14621   }
14622 
14623   // We only support broadcasting from 128-bit vectors to minimize the
14624   // number of patterns we need to deal with in isel. So extract down to
14625   // 128-bits, removing as many bitcasts as possible.
14626   if (V.getValueSizeInBits() > 128)
14627     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
14628 
14629   // Otherwise cast V to a vector with the same element type as VT, but
14630   // possibly narrower than VT. Then perform the broadcast.
14631   unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
14632   MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
14633   return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
14634 }
14635 
14636 // Check for whether we can use INSERTPS to perform the shuffle. We only use
14637 // INSERTPS when the V1 elements are already in the correct locations
14638 // because otherwise we can just always use two SHUFPS instructions which
14639 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
14640 // perform INSERTPS if a single V1 element is out of place and all V2
14641 // elements are zeroable.
14642 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
14643                                    unsigned &InsertPSMask,
14644                                    const APInt &Zeroable,
14645                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
14646   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
14647   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
14648   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14649 
14650   // Attempt to match INSERTPS with one element from VA or VB being
14651   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
14652   // are updated.
14653   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
14654                              ArrayRef<int> CandidateMask) {
14655     unsigned ZMask = 0;
14656     int VADstIndex = -1;
14657     int VBDstIndex = -1;
14658     bool VAUsedInPlace = false;
14659 
14660     for (int i = 0; i < 4; ++i) {
14661       // Synthesize a zero mask from the zeroable elements (includes undefs).
14662       if (Zeroable[i]) {
14663         ZMask |= 1 << i;
14664         continue;
14665       }
14666 
14667       // Flag if we use any VA inputs in place.
14668       if (i == CandidateMask[i]) {
14669         VAUsedInPlace = true;
14670         continue;
14671       }
14672 
14673       // We can only insert a single non-zeroable element.
14674       if (VADstIndex >= 0 || VBDstIndex >= 0)
14675         return false;
14676 
14677       if (CandidateMask[i] < 4) {
14678         // VA input out of place for insertion.
14679         VADstIndex = i;
14680       } else {
14681         // VB input for insertion.
14682         VBDstIndex = i;
14683       }
14684     }
14685 
14686     // Don't bother if we have no (non-zeroable) element for insertion.
14687     if (VADstIndex < 0 && VBDstIndex < 0)
14688       return false;
14689 
14690     // Determine element insertion src/dst indices. The src index is from the
14691     // start of the inserted vector, not the start of the concatenated vector.
14692     unsigned VBSrcIndex = 0;
14693     if (VADstIndex >= 0) {
14694       // If we have a VA input out of place, we use VA as the V2 element
14695       // insertion and don't use the original V2 at all.
14696       VBSrcIndex = CandidateMask[VADstIndex];
14697       VBDstIndex = VADstIndex;
14698       VB = VA;
14699     } else {
14700       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
14701     }
14702 
14703     // If no V1 inputs are used in place, then the result is created only from
14704     // the zero mask and the V2 insertion - so remove V1 dependency.
14705     if (!VAUsedInPlace)
14706       VA = DAG.getUNDEF(MVT::v4f32);
14707 
14708     // Update V1, V2 and InsertPSMask accordingly.
14709     V1 = VA;
14710     V2 = VB;
14711 
14712     // Insert the V2 element into the desired position.
14713     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
14714     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
14715     return true;
14716   };
14717 
14718   if (matchAsInsertPS(V1, V2, Mask))
14719     return true;
14720 
14721   // Commute and try again.
14722   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
14723   ShuffleVectorSDNode::commuteMask(CommutedMask);
14724   if (matchAsInsertPS(V2, V1, CommutedMask))
14725     return true;
14726 
14727   return false;
14728 }
14729 
14730 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
14731                                       ArrayRef<int> Mask, const APInt &Zeroable,
14732                                       SelectionDAG &DAG) {
14733   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14734   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14735 
14736   // Attempt to match the insertps pattern.
14737   unsigned InsertPSMask = 0;
14738   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
14739     return SDValue();
14740 
14741   // Insert the V2 element into the desired position.
14742   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
14743                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
14744 }
14745 
14746 /// Try to lower a shuffle as a permute of the inputs followed by an
14747 /// UNPCK instruction.
14748 ///
14749 /// This specifically targets cases where we end up with alternating between
14750 /// the two inputs, and so can permute them into something that feeds a single
14751 /// UNPCK instruction. Note that this routine only targets integer vectors
14752 /// because for floating point vectors we have a generalized SHUFPS lowering
14753 /// strategy that handles everything that doesn't *exactly* match an unpack,
14754 /// making this clever lowering unnecessary.
14755 static SDValue lowerShuffleAsPermuteAndUnpack(
14756     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14757     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14758   assert(!VT.isFloatingPoint() &&
14759          "This routine only supports integer vectors.");
14760   assert(VT.is128BitVector() &&
14761          "This routine only works on 128-bit vectors.");
14762   assert(!V2.isUndef() &&
14763          "This routine should only be used when blending two inputs.");
14764   assert(Mask.size() >= 2 && "Single element masks are invalid.");
14765 
14766   int Size = Mask.size();
14767 
14768   int NumLoInputs =
14769       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
14770   int NumHiInputs =
14771       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
14772 
14773   bool UnpackLo = NumLoInputs >= NumHiInputs;
14774 
14775   auto TryUnpack = [&](int ScalarSize, int Scale) {
14776     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
14777     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
14778 
14779     for (int i = 0; i < Size; ++i) {
14780       if (Mask[i] < 0)
14781         continue;
14782 
14783       // Each element of the unpack contains Scale elements from this mask.
14784       int UnpackIdx = i / Scale;
14785 
14786       // We only handle the case where V1 feeds the first slots of the unpack.
14787       // We rely on canonicalization to ensure this is the case.
14788       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
14789         return SDValue();
14790 
14791       // Setup the mask for this input. The indexing is tricky as we have to
14792       // handle the unpack stride.
14793       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
14794       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
14795           Mask[i] % Size;
14796     }
14797 
14798     // If we will have to shuffle both inputs to use the unpack, check whether
14799     // we can just unpack first and shuffle the result. If so, skip this unpack.
14800     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
14801         !isNoopShuffleMask(V2Mask))
14802       return SDValue();
14803 
14804     // Shuffle the inputs into place.
14805     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
14806     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
14807 
14808     // Cast the inputs to the type we will use to unpack them.
14809     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
14810     V1 = DAG.getBitcast(UnpackVT, V1);
14811     V2 = DAG.getBitcast(UnpackVT, V2);
14812 
14813     // Unpack the inputs and cast the result back to the desired type.
14814     return DAG.getBitcast(
14815         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14816                         UnpackVT, V1, V2));
14817   };
14818 
14819   // We try each unpack from the largest to the smallest to try and find one
14820   // that fits this mask.
14821   int OrigScalarSize = VT.getScalarSizeInBits();
14822   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
14823     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
14824       return Unpack;
14825 
14826   // If we're shuffling with a zero vector then we're better off not doing
14827   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
14828   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
14829       ISD::isBuildVectorAllZeros(V2.getNode()))
14830     return SDValue();
14831 
14832   // If none of the unpack-rooted lowerings worked (or were profitable) try an
14833   // initial unpack.
14834   if (NumLoInputs == 0 || NumHiInputs == 0) {
14835     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
14836            "We have to have *some* inputs!");
14837     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
14838 
14839     // FIXME: We could consider the total complexity of the permute of each
14840     // possible unpacking. Or at the least we should consider how many
14841     // half-crossings are created.
14842     // FIXME: We could consider commuting the unpacks.
14843 
14844     SmallVector<int, 32> PermMask((unsigned)Size, -1);
14845     for (int i = 0; i < Size; ++i) {
14846       if (Mask[i] < 0)
14847         continue;
14848 
14849       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
14850 
14851       PermMask[i] =
14852           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
14853     }
14854     return DAG.getVectorShuffle(
14855         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
14856                             DL, VT, V1, V2),
14857         DAG.getUNDEF(VT), PermMask);
14858   }
14859 
14860   return SDValue();
14861 }
14862 
14863 /// Handle lowering of 2-lane 64-bit floating point shuffles.
14864 ///
14865 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
14866 /// support for floating point shuffles but not integer shuffles. These
14867 /// instructions will incur a domain crossing penalty on some chips though so
14868 /// it is better to avoid lowering through this for integer vectors where
14869 /// possible.
14870 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14871                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14872                                  const X86Subtarget &Subtarget,
14873                                  SelectionDAG &DAG) {
14874   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
14875   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
14876   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
14877 
14878   if (V2.isUndef()) {
14879     // Check for being able to broadcast a single element.
14880     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
14881                                                     Mask, Subtarget, DAG))
14882       return Broadcast;
14883 
14884     // Straight shuffle of a single input vector. Simulate this by using the
14885     // single input as both of the "inputs" to this instruction..
14886     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
14887 
14888     if (Subtarget.hasAVX()) {
14889       // If we have AVX, we can use VPERMILPS which will allow folding a load
14890       // into the shuffle.
14891       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
14892                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14893     }
14894 
14895     return DAG.getNode(
14896         X86ISD::SHUFP, DL, MVT::v2f64,
14897         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
14898         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
14899         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14900   }
14901   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
14902   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
14903   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
14904   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
14905 
14906   if (Subtarget.hasAVX2())
14907     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14908       return Extract;
14909 
14910   // When loading a scalar and then shuffling it into a vector we can often do
14911   // the insertion cheaply.
14912   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14913           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14914     return Insertion;
14915   // Try inverting the insertion since for v2 masks it is easy to do and we
14916   // can't reliably sort the mask one way or the other.
14917   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
14918                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
14919   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14920           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14921     return Insertion;
14922 
14923   // Try to use one of the special instruction patterns to handle two common
14924   // blend patterns if a zero-blend above didn't work.
14925   if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
14926       isShuffleEquivalent(Mask, {1, 3}, V1, V2))
14927     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
14928       // We can either use a special instruction to load over the low double or
14929       // to move just the low double.
14930       return DAG.getNode(
14931           X86ISD::MOVSD, DL, MVT::v2f64, V2,
14932           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
14933 
14934   if (Subtarget.hasSSE41())
14935     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
14936                                             Zeroable, Subtarget, DAG))
14937       return Blend;
14938 
14939   // Use dedicated unpack instructions for masks that match their pattern.
14940   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
14941     return V;
14942 
14943   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
14944   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
14945                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14946 }
14947 
14948 /// Handle lowering of 2-lane 64-bit integer shuffles.
14949 ///
14950 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
14951 /// the integer unit to minimize domain crossing penalties. However, for blends
14952 /// it falls back to the floating point shuffle operation with appropriate bit
14953 /// casting.
14954 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14955                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14956                                  const X86Subtarget &Subtarget,
14957                                  SelectionDAG &DAG) {
14958   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
14959   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
14960   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
14961 
14962   if (V2.isUndef()) {
14963     // Check for being able to broadcast a single element.
14964     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
14965                                                     Mask, Subtarget, DAG))
14966       return Broadcast;
14967 
14968     // Straight shuffle of a single input vector. For everything from SSE2
14969     // onward this has a single fast instruction with no scary immediates.
14970     // We have to map the mask as it is actually a v4i32 shuffle instruction.
14971     V1 = DAG.getBitcast(MVT::v4i32, V1);
14972     int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
14973                           Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
14974                           Mask[1] < 0 ? -1 : (Mask[1] * 2),
14975                           Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
14976     return DAG.getBitcast(
14977         MVT::v2i64,
14978         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14979                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
14980   }
14981   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
14982   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
14983   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
14984   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
14985 
14986   if (Subtarget.hasAVX2())
14987     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14988       return Extract;
14989 
14990   // Try to use shift instructions.
14991   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
14992                                           Zeroable, Subtarget, DAG))
14993     return Shift;
14994 
14995   // When loading a scalar and then shuffling it into a vector we can often do
14996   // the insertion cheaply.
14997   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14998           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14999     return Insertion;
15000   // Try inverting the insertion since for v2 masks it is easy to do and we
15001   // can't reliably sort the mask one way or the other.
15002   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
15003   if (SDValue Insertion = lowerShuffleAsElementInsertion(
15004           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
15005     return Insertion;
15006 
15007   // We have different paths for blend lowering, but they all must use the
15008   // *exact* same predicate.
15009   bool IsBlendSupported = Subtarget.hasSSE41();
15010   if (IsBlendSupported)
15011     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
15012                                             Zeroable, Subtarget, DAG))
15013       return Blend;
15014 
15015   // Use dedicated unpack instructions for masks that match their pattern.
15016   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
15017     return V;
15018 
15019   // Try to use byte rotation instructions.
15020   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
15021   if (Subtarget.hasSSSE3()) {
15022     if (Subtarget.hasVLX())
15023       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
15024                                                 Subtarget, DAG))
15025         return Rotate;
15026 
15027     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
15028                                                   Subtarget, DAG))
15029       return Rotate;
15030   }
15031 
15032   // If we have direct support for blends, we should lower by decomposing into
15033   // a permute. That will be faster than the domain cross.
15034   if (IsBlendSupported)
15035     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
15036                                                 Subtarget, DAG);
15037 
15038   // We implement this with SHUFPD which is pretty lame because it will likely
15039   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
15040   // However, all the alternatives are still more cycles and newer chips don't
15041   // have this problem. It would be really nice if x86 had better shuffles here.
15042   V1 = DAG.getBitcast(MVT::v2f64, V1);
15043   V2 = DAG.getBitcast(MVT::v2f64, V2);
15044   return DAG.getBitcast(MVT::v2i64,
15045                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
15046 }
15047 
15048 /// Lower a vector shuffle using the SHUFPS instruction.
15049 ///
15050 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
15051 /// It makes no assumptions about whether this is the *best* lowering, it simply
15052 /// uses it.
15053 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
15054                                       ArrayRef<int> Mask, SDValue V1,
15055                                       SDValue V2, SelectionDAG &DAG) {
15056   SDValue LowV = V1, HighV = V2;
15057   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
15058   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
15059 
15060   if (NumV2Elements == 1) {
15061     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
15062 
15063     // Compute the index adjacent to V2Index and in the same half by toggling
15064     // the low bit.
15065     int V2AdjIndex = V2Index ^ 1;
15066 
15067     if (Mask[V2AdjIndex] < 0) {
15068       // Handles all the cases where we have a single V2 element and an undef.
15069       // This will only ever happen in the high lanes because we commute the
15070       // vector otherwise.
15071       if (V2Index < 2)
15072         std::swap(LowV, HighV);
15073       NewMask[V2Index] -= 4;
15074     } else {
15075       // Handle the case where the V2 element ends up adjacent to a V1 element.
15076       // To make this work, blend them together as the first step.
15077       int V1Index = V2AdjIndex;
15078       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
15079       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
15080                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
15081 
15082       // Now proceed to reconstruct the final blend as we have the necessary
15083       // high or low half formed.
15084       if (V2Index < 2) {
15085         LowV = V2;
15086         HighV = V1;
15087       } else {
15088         HighV = V2;
15089       }
15090       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
15091       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
15092     }
15093   } else if (NumV2Elements == 2) {
15094     if (Mask[0] < 4 && Mask[1] < 4) {
15095       // Handle the easy case where we have V1 in the low lanes and V2 in the
15096       // high lanes.
15097       NewMask[2] -= 4;
15098       NewMask[3] -= 4;
15099     } else if (Mask[2] < 4 && Mask[3] < 4) {
15100       // We also handle the reversed case because this utility may get called
15101       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
15102       // arrange things in the right direction.
15103       NewMask[0] -= 4;
15104       NewMask[1] -= 4;
15105       HighV = V1;
15106       LowV = V2;
15107     } else {
15108       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
15109       // trying to place elements directly, just blend them and set up the final
15110       // shuffle to place them.
15111 
15112       // The first two blend mask elements are for V1, the second two are for
15113       // V2.
15114       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
15115                           Mask[2] < 4 ? Mask[2] : Mask[3],
15116                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
15117                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
15118       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
15119                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
15120 
15121       // Now we do a normal shuffle of V1 by giving V1 as both operands to
15122       // a blend.
15123       LowV = HighV = V1;
15124       NewMask[0] = Mask[0] < 4 ? 0 : 2;
15125       NewMask[1] = Mask[0] < 4 ? 2 : 0;
15126       NewMask[2] = Mask[2] < 4 ? 1 : 3;
15127       NewMask[3] = Mask[2] < 4 ? 3 : 1;
15128     }
15129   } else if (NumV2Elements == 3) {
15130     // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
15131     // we can get here due to other paths (e.g repeated mask matching) that we
15132     // don't want to do another round of lowerVECTOR_SHUFFLE.
15133     ShuffleVectorSDNode::commuteMask(NewMask);
15134     return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
15135   }
15136   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
15137                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
15138 }
15139 
15140 /// Lower 4-lane 32-bit floating point shuffles.
15141 ///
15142 /// Uses instructions exclusively from the floating point unit to minimize
15143 /// domain crossing penalties, as these are sufficient to implement all v4f32
15144 /// shuffles.
15145 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15146                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15147                                  const X86Subtarget &Subtarget,
15148                                  SelectionDAG &DAG) {
15149   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
15150   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
15151   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15152 
15153   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
15154 
15155   if (NumV2Elements == 0) {
15156     // Check for being able to broadcast a single element.
15157     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
15158                                                     Mask, Subtarget, DAG))
15159       return Broadcast;
15160 
15161     // Use even/odd duplicate instructions for masks that match their pattern.
15162     if (Subtarget.hasSSE3()) {
15163       if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
15164         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
15165       if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
15166         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
15167     }
15168 
15169     if (Subtarget.hasAVX()) {
15170       // If we have AVX, we can use VPERMILPS which will allow folding a load
15171       // into the shuffle.
15172       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
15173                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15174     }
15175 
15176     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
15177     // in SSE1 because otherwise they are widened to v2f64 and never get here.
15178     if (!Subtarget.hasSSE2()) {
15179       if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
15180         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
15181       if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
15182         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
15183     }
15184 
15185     // Otherwise, use a straight shuffle of a single input vector. We pass the
15186     // input vector to both operands to simulate this with a SHUFPS.
15187     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
15188                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15189   }
15190 
15191   if (Subtarget.hasAVX2())
15192     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
15193       return Extract;
15194 
15195   // There are special ways we can lower some single-element blends. However, we
15196   // have custom ways we can lower more complex single-element blends below that
15197   // we defer to if both this and BLENDPS fail to match, so restrict this to
15198   // when the V2 input is targeting element 0 of the mask -- that is the fast
15199   // case here.
15200   if (NumV2Elements == 1 && Mask[0] >= 4)
15201     if (SDValue V = lowerShuffleAsElementInsertion(
15202             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
15203       return V;
15204 
15205   if (Subtarget.hasSSE41()) {
15206     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
15207                                             Zeroable, Subtarget, DAG))
15208       return Blend;
15209 
15210     // Use INSERTPS if we can complete the shuffle efficiently.
15211     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
15212       return V;
15213 
15214     if (!isSingleSHUFPSMask(Mask))
15215       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
15216                                                             V2, Mask, DAG))
15217         return BlendPerm;
15218   }
15219 
15220   // Use low/high mov instructions. These are only valid in SSE1 because
15221   // otherwise they are widened to v2f64 and never get here.
15222   if (!Subtarget.hasSSE2()) {
15223     if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
15224       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
15225     if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
15226       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
15227   }
15228 
15229   // Use dedicated unpack instructions for masks that match their pattern.
15230   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
15231     return V;
15232 
15233   // Otherwise fall back to a SHUFPS lowering strategy.
15234   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
15235 }
15236 
15237 /// Lower 4-lane i32 vector shuffles.
15238 ///
15239 /// We try to handle these with integer-domain shuffles where we can, but for
15240 /// blends we use the floating point domain blend instructions.
15241 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15242                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15243                                  const X86Subtarget &Subtarget,
15244                                  SelectionDAG &DAG) {
15245   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
15246   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
15247   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15248 
15249   // Whenever we can lower this as a zext, that instruction is strictly faster
15250   // than any alternative. It also allows us to fold memory operands into the
15251   // shuffle in many cases.
15252   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
15253                                                    Zeroable, Subtarget, DAG))
15254     return ZExt;
15255 
15256   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
15257 
15258   if (NumV2Elements == 0) {
15259     // Try to use broadcast unless the mask only has one non-undef element.
15260     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
15261       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
15262                                                       Mask, Subtarget, DAG))
15263         return Broadcast;
15264     }
15265 
15266     // Straight shuffle of a single input vector. For everything from SSE2
15267     // onward this has a single fast instruction with no scary immediates.
15268     // We coerce the shuffle pattern to be compatible with UNPCK instructions
15269     // but we aren't actually going to use the UNPCK instruction because doing
15270     // so prevents folding a load into this instruction or making a copy.
15271     const int UnpackLoMask[] = {0, 0, 1, 1};
15272     const int UnpackHiMask[] = {2, 2, 3, 3};
15273     if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
15274       Mask = UnpackLoMask;
15275     else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
15276       Mask = UnpackHiMask;
15277 
15278     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
15279                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15280   }
15281 
15282   if (Subtarget.hasAVX2())
15283     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
15284       return Extract;
15285 
15286   // Try to use shift instructions.
15287   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
15288                                           Zeroable, Subtarget, DAG))
15289     return Shift;
15290 
15291   // There are special ways we can lower some single-element blends.
15292   if (NumV2Elements == 1)
15293     if (SDValue V = lowerShuffleAsElementInsertion(
15294             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
15295       return V;
15296 
15297   // We have different paths for blend lowering, but they all must use the
15298   // *exact* same predicate.
15299   bool IsBlendSupported = Subtarget.hasSSE41();
15300   if (IsBlendSupported)
15301     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
15302                                             Zeroable, Subtarget, DAG))
15303       return Blend;
15304 
15305   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
15306                                              Zeroable, Subtarget, DAG))
15307     return Masked;
15308 
15309   // Use dedicated unpack instructions for masks that match their pattern.
15310   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
15311     return V;
15312 
15313   // Try to use byte rotation instructions.
15314   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
15315   if (Subtarget.hasSSSE3()) {
15316     if (Subtarget.hasVLX())
15317       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
15318                                                 Subtarget, DAG))
15319         return Rotate;
15320 
15321     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
15322                                                   Subtarget, DAG))
15323       return Rotate;
15324   }
15325 
15326   // Assume that a single SHUFPS is faster than an alternative sequence of
15327   // multiple instructions (even if the CPU has a domain penalty).
15328   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
15329   if (!isSingleSHUFPSMask(Mask)) {
15330     // If we have direct support for blends, we should lower by decomposing into
15331     // a permute. That will be faster than the domain cross.
15332     if (IsBlendSupported)
15333       return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
15334                                                   Subtarget, DAG);
15335 
15336     // Try to lower by permuting the inputs into an unpack instruction.
15337     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
15338                                                         Mask, Subtarget, DAG))
15339       return Unpack;
15340   }
15341 
15342   // We implement this with SHUFPS because it can blend from two vectors.
15343   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
15344   // up the inputs, bypassing domain shift penalties that we would incur if we
15345   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
15346   // relevant.
15347   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
15348   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
15349   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
15350   return DAG.getBitcast(MVT::v4i32, ShufPS);
15351 }
15352 
15353 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
15354 /// shuffle lowering, and the most complex part.
15355 ///
15356 /// The lowering strategy is to try to form pairs of input lanes which are
15357 /// targeted at the same half of the final vector, and then use a dword shuffle
15358 /// to place them onto the right half, and finally unpack the paired lanes into
15359 /// their final position.
15360 ///
15361 /// The exact breakdown of how to form these dword pairs and align them on the
15362 /// correct sides is really tricky. See the comments within the function for
15363 /// more of the details.
15364 ///
15365 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
15366 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
15367 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
15368 /// vector, form the analogous 128-bit 8-element Mask.
15369 static SDValue lowerV8I16GeneralSingleInputShuffle(
15370     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
15371     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15372   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
15373   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
15374 
15375   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
15376   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
15377   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
15378 
15379   // Attempt to directly match PSHUFLW or PSHUFHW.
15380   if (isUndefOrInRange(LoMask, 0, 4) &&
15381       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
15382     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15383                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
15384   }
15385   if (isUndefOrInRange(HiMask, 4, 8) &&
15386       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
15387     for (int i = 0; i != 4; ++i)
15388       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
15389     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15390                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
15391   }
15392 
15393   SmallVector<int, 4> LoInputs;
15394   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
15395   array_pod_sort(LoInputs.begin(), LoInputs.end());
15396   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
15397   SmallVector<int, 4> HiInputs;
15398   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
15399   array_pod_sort(HiInputs.begin(), HiInputs.end());
15400   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
15401   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
15402   int NumHToL = LoInputs.size() - NumLToL;
15403   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
15404   int NumHToH = HiInputs.size() - NumLToH;
15405   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
15406   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
15407   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
15408   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
15409 
15410   // If we are shuffling values from one half - check how many different DWORD
15411   // pairs we need to create. If only 1 or 2 then we can perform this as a
15412   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
15413   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
15414                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
15415     V = DAG.getNode(ShufWOp, DL, VT, V,
15416                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
15417     V = DAG.getBitcast(PSHUFDVT, V);
15418     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
15419                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
15420     return DAG.getBitcast(VT, V);
15421   };
15422 
15423   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
15424     int PSHUFDMask[4] = { -1, -1, -1, -1 };
15425     SmallVector<std::pair<int, int>, 4> DWordPairs;
15426     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
15427 
15428     // Collect the different DWORD pairs.
15429     for (int DWord = 0; DWord != 4; ++DWord) {
15430       int M0 = Mask[2 * DWord + 0];
15431       int M1 = Mask[2 * DWord + 1];
15432       M0 = (M0 >= 0 ? M0 % 4 : M0);
15433       M1 = (M1 >= 0 ? M1 % 4 : M1);
15434       if (M0 < 0 && M1 < 0)
15435         continue;
15436 
15437       bool Match = false;
15438       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
15439         auto &DWordPair = DWordPairs[j];
15440         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
15441             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
15442           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
15443           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
15444           PSHUFDMask[DWord] = DOffset + j;
15445           Match = true;
15446           break;
15447         }
15448       }
15449       if (!Match) {
15450         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
15451         DWordPairs.push_back(std::make_pair(M0, M1));
15452       }
15453     }
15454 
15455     if (DWordPairs.size() <= 2) {
15456       DWordPairs.resize(2, std::make_pair(-1, -1));
15457       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
15458                               DWordPairs[1].first, DWordPairs[1].second};
15459       if ((NumHToL + NumHToH) == 0)
15460         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
15461       if ((NumLToL + NumLToH) == 0)
15462         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
15463     }
15464   }
15465 
15466   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
15467   // such inputs we can swap two of the dwords across the half mark and end up
15468   // with <=2 inputs to each half in each half. Once there, we can fall through
15469   // to the generic code below. For example:
15470   //
15471   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
15472   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
15473   //
15474   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
15475   // and an existing 2-into-2 on the other half. In this case we may have to
15476   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
15477   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
15478   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
15479   // because any other situation (including a 3-into-1 or 1-into-3 in the other
15480   // half than the one we target for fixing) will be fixed when we re-enter this
15481   // path. We will also combine away any sequence of PSHUFD instructions that
15482   // result into a single instruction. Here is an example of the tricky case:
15483   //
15484   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
15485   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
15486   //
15487   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
15488   //
15489   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
15490   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
15491   //
15492   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
15493   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
15494   //
15495   // The result is fine to be handled by the generic logic.
15496   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
15497                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
15498                           int AOffset, int BOffset) {
15499     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
15500            "Must call this with A having 3 or 1 inputs from the A half.");
15501     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
15502            "Must call this with B having 1 or 3 inputs from the B half.");
15503     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
15504            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
15505 
15506     bool ThreeAInputs = AToAInputs.size() == 3;
15507 
15508     // Compute the index of dword with only one word among the three inputs in
15509     // a half by taking the sum of the half with three inputs and subtracting
15510     // the sum of the actual three inputs. The difference is the remaining
15511     // slot.
15512     int ADWord = 0, BDWord = 0;
15513     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
15514     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
15515     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
15516     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
15517     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
15518     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
15519     int TripleNonInputIdx =
15520         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
15521     TripleDWord = TripleNonInputIdx / 2;
15522 
15523     // We use xor with one to compute the adjacent DWord to whichever one the
15524     // OneInput is in.
15525     OneInputDWord = (OneInput / 2) ^ 1;
15526 
15527     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
15528     // and BToA inputs. If there is also such a problem with the BToB and AToB
15529     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
15530     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
15531     // is essential that we don't *create* a 3<-1 as then we might oscillate.
15532     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
15533       // Compute how many inputs will be flipped by swapping these DWords. We
15534       // need
15535       // to balance this to ensure we don't form a 3-1 shuffle in the other
15536       // half.
15537       int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
15538                                  llvm::count(AToBInputs, 2 * ADWord + 1);
15539       int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
15540                                  llvm::count(BToBInputs, 2 * BDWord + 1);
15541       if ((NumFlippedAToBInputs == 1 &&
15542            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
15543           (NumFlippedBToBInputs == 1 &&
15544            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
15545         // We choose whether to fix the A half or B half based on whether that
15546         // half has zero flipped inputs. At zero, we may not be able to fix it
15547         // with that half. We also bias towards fixing the B half because that
15548         // will more commonly be the high half, and we have to bias one way.
15549         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
15550                                                        ArrayRef<int> Inputs) {
15551           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
15552           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
15553           // Determine whether the free index is in the flipped dword or the
15554           // unflipped dword based on where the pinned index is. We use this bit
15555           // in an xor to conditionally select the adjacent dword.
15556           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
15557           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
15558           if (IsFixIdxInput == IsFixFreeIdxInput)
15559             FixFreeIdx += 1;
15560           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
15561           assert(IsFixIdxInput != IsFixFreeIdxInput &&
15562                  "We need to be changing the number of flipped inputs!");
15563           int PSHUFHalfMask[] = {0, 1, 2, 3};
15564           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
15565           V = DAG.getNode(
15566               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
15567               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
15568               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
15569 
15570           for (int &M : Mask)
15571             if (M >= 0 && M == FixIdx)
15572               M = FixFreeIdx;
15573             else if (M >= 0 && M == FixFreeIdx)
15574               M = FixIdx;
15575         };
15576         if (NumFlippedBToBInputs != 0) {
15577           int BPinnedIdx =
15578               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
15579           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
15580         } else {
15581           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
15582           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
15583           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
15584         }
15585       }
15586     }
15587 
15588     int PSHUFDMask[] = {0, 1, 2, 3};
15589     PSHUFDMask[ADWord] = BDWord;
15590     PSHUFDMask[BDWord] = ADWord;
15591     V = DAG.getBitcast(
15592         VT,
15593         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
15594                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15595 
15596     // Adjust the mask to match the new locations of A and B.
15597     for (int &M : Mask)
15598       if (M >= 0 && M/2 == ADWord)
15599         M = 2 * BDWord + M % 2;
15600       else if (M >= 0 && M/2 == BDWord)
15601         M = 2 * ADWord + M % 2;
15602 
15603     // Recurse back into this routine to re-compute state now that this isn't
15604     // a 3 and 1 problem.
15605     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
15606   };
15607   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
15608     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
15609   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
15610     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
15611 
15612   // At this point there are at most two inputs to the low and high halves from
15613   // each half. That means the inputs can always be grouped into dwords and
15614   // those dwords can then be moved to the correct half with a dword shuffle.
15615   // We use at most one low and one high word shuffle to collect these paired
15616   // inputs into dwords, and finally a dword shuffle to place them.
15617   int PSHUFLMask[4] = {-1, -1, -1, -1};
15618   int PSHUFHMask[4] = {-1, -1, -1, -1};
15619   int PSHUFDMask[4] = {-1, -1, -1, -1};
15620 
15621   // First fix the masks for all the inputs that are staying in their
15622   // original halves. This will then dictate the targets of the cross-half
15623   // shuffles.
15624   auto fixInPlaceInputs =
15625       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
15626                     MutableArrayRef<int> SourceHalfMask,
15627                     MutableArrayRef<int> HalfMask, int HalfOffset) {
15628     if (InPlaceInputs.empty())
15629       return;
15630     if (InPlaceInputs.size() == 1) {
15631       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
15632           InPlaceInputs[0] - HalfOffset;
15633       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
15634       return;
15635     }
15636     if (IncomingInputs.empty()) {
15637       // Just fix all of the in place inputs.
15638       for (int Input : InPlaceInputs) {
15639         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
15640         PSHUFDMask[Input / 2] = Input / 2;
15641       }
15642       return;
15643     }
15644 
15645     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
15646     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
15647         InPlaceInputs[0] - HalfOffset;
15648     // Put the second input next to the first so that they are packed into
15649     // a dword. We find the adjacent index by toggling the low bit.
15650     int AdjIndex = InPlaceInputs[0] ^ 1;
15651     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
15652     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
15653     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
15654   };
15655   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
15656   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
15657 
15658   // Now gather the cross-half inputs and place them into a free dword of
15659   // their target half.
15660   // FIXME: This operation could almost certainly be simplified dramatically to
15661   // look more like the 3-1 fixing operation.
15662   auto moveInputsToRightHalf = [&PSHUFDMask](
15663       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
15664       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
15665       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
15666       int DestOffset) {
15667     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
15668       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
15669     };
15670     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
15671                                                int Word) {
15672       int LowWord = Word & ~1;
15673       int HighWord = Word | 1;
15674       return isWordClobbered(SourceHalfMask, LowWord) ||
15675              isWordClobbered(SourceHalfMask, HighWord);
15676     };
15677 
15678     if (IncomingInputs.empty())
15679       return;
15680 
15681     if (ExistingInputs.empty()) {
15682       // Map any dwords with inputs from them into the right half.
15683       for (int Input : IncomingInputs) {
15684         // If the source half mask maps over the inputs, turn those into
15685         // swaps and use the swapped lane.
15686         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
15687           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
15688             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
15689                 Input - SourceOffset;
15690             // We have to swap the uses in our half mask in one sweep.
15691             for (int &M : HalfMask)
15692               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
15693                 M = Input;
15694               else if (M == Input)
15695                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
15696           } else {
15697             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
15698                        Input - SourceOffset &&
15699                    "Previous placement doesn't match!");
15700           }
15701           // Note that this correctly re-maps both when we do a swap and when
15702           // we observe the other side of the swap above. We rely on that to
15703           // avoid swapping the members of the input list directly.
15704           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
15705         }
15706 
15707         // Map the input's dword into the correct half.
15708         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
15709           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
15710         else
15711           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
15712                      Input / 2 &&
15713                  "Previous placement doesn't match!");
15714       }
15715 
15716       // And just directly shift any other-half mask elements to be same-half
15717       // as we will have mirrored the dword containing the element into the
15718       // same position within that half.
15719       for (int &M : HalfMask)
15720         if (M >= SourceOffset && M < SourceOffset + 4) {
15721           M = M - SourceOffset + DestOffset;
15722           assert(M >= 0 && "This should never wrap below zero!");
15723         }
15724       return;
15725     }
15726 
15727     // Ensure we have the input in a viable dword of its current half. This
15728     // is particularly tricky because the original position may be clobbered
15729     // by inputs being moved and *staying* in that half.
15730     if (IncomingInputs.size() == 1) {
15731       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
15732         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
15733                          SourceOffset;
15734         SourceHalfMask[InputFixed - SourceOffset] =
15735             IncomingInputs[0] - SourceOffset;
15736         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
15737                      InputFixed);
15738         IncomingInputs[0] = InputFixed;
15739       }
15740     } else if (IncomingInputs.size() == 2) {
15741       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
15742           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
15743         // We have two non-adjacent or clobbered inputs we need to extract from
15744         // the source half. To do this, we need to map them into some adjacent
15745         // dword slot in the source mask.
15746         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
15747                               IncomingInputs[1] - SourceOffset};
15748 
15749         // If there is a free slot in the source half mask adjacent to one of
15750         // the inputs, place the other input in it. We use (Index XOR 1) to
15751         // compute an adjacent index.
15752         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
15753             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
15754           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
15755           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
15756           InputsFixed[1] = InputsFixed[0] ^ 1;
15757         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
15758                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
15759           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
15760           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
15761           InputsFixed[0] = InputsFixed[1] ^ 1;
15762         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
15763                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
15764           // The two inputs are in the same DWord but it is clobbered and the
15765           // adjacent DWord isn't used at all. Move both inputs to the free
15766           // slot.
15767           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
15768           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
15769           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
15770           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
15771         } else {
15772           // The only way we hit this point is if there is no clobbering
15773           // (because there are no off-half inputs to this half) and there is no
15774           // free slot adjacent to one of the inputs. In this case, we have to
15775           // swap an input with a non-input.
15776           for (int i = 0; i < 4; ++i)
15777             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
15778                    "We can't handle any clobbers here!");
15779           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
15780                  "Cannot have adjacent inputs here!");
15781 
15782           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
15783           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
15784 
15785           // We also have to update the final source mask in this case because
15786           // it may need to undo the above swap.
15787           for (int &M : FinalSourceHalfMask)
15788             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
15789               M = InputsFixed[1] + SourceOffset;
15790             else if (M == InputsFixed[1] + SourceOffset)
15791               M = (InputsFixed[0] ^ 1) + SourceOffset;
15792 
15793           InputsFixed[1] = InputsFixed[0] ^ 1;
15794         }
15795 
15796         // Point everything at the fixed inputs.
15797         for (int &M : HalfMask)
15798           if (M == IncomingInputs[0])
15799             M = InputsFixed[0] + SourceOffset;
15800           else if (M == IncomingInputs[1])
15801             M = InputsFixed[1] + SourceOffset;
15802 
15803         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
15804         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
15805       }
15806     } else {
15807       llvm_unreachable("Unhandled input size!");
15808     }
15809 
15810     // Now hoist the DWord down to the right half.
15811     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
15812     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
15813     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
15814     for (int &M : HalfMask)
15815       for (int Input : IncomingInputs)
15816         if (M == Input)
15817           M = FreeDWord * 2 + Input % 2;
15818   };
15819   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
15820                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
15821   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
15822                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
15823 
15824   // Now enact all the shuffles we've computed to move the inputs into their
15825   // target half.
15826   if (!isNoopShuffleMask(PSHUFLMask))
15827     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15828                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
15829   if (!isNoopShuffleMask(PSHUFHMask))
15830     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15831                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
15832   if (!isNoopShuffleMask(PSHUFDMask))
15833     V = DAG.getBitcast(
15834         VT,
15835         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
15836                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15837 
15838   // At this point, each half should contain all its inputs, and we can then
15839   // just shuffle them into their final position.
15840   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
15841          "Failed to lift all the high half inputs to the low mask!");
15842   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
15843          "Failed to lift all the low half inputs to the high mask!");
15844 
15845   // Do a half shuffle for the low mask.
15846   if (!isNoopShuffleMask(LoMask))
15847     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15848                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
15849 
15850   // Do a half shuffle with the high mask after shifting its values down.
15851   for (int &M : HiMask)
15852     if (M >= 0)
15853       M -= 4;
15854   if (!isNoopShuffleMask(HiMask))
15855     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15856                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
15857 
15858   return V;
15859 }
15860 
15861 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
15862 /// blend if only one input is used.
15863 static SDValue lowerShuffleAsBlendOfPSHUFBs(
15864     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15865     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
15866   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
15867          "Lane crossing shuffle masks not supported");
15868 
15869   int NumBytes = VT.getSizeInBits() / 8;
15870   int Size = Mask.size();
15871   int Scale = NumBytes / Size;
15872 
15873   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
15874   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
15875   V1InUse = false;
15876   V2InUse = false;
15877 
15878   for (int i = 0; i < NumBytes; ++i) {
15879     int M = Mask[i / Scale];
15880     if (M < 0)
15881       continue;
15882 
15883     const int ZeroMask = 0x80;
15884     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
15885     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
15886     if (Zeroable[i / Scale])
15887       V1Idx = V2Idx = ZeroMask;
15888 
15889     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
15890     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
15891     V1InUse |= (ZeroMask != V1Idx);
15892     V2InUse |= (ZeroMask != V2Idx);
15893   }
15894 
15895   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
15896   if (V1InUse)
15897     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
15898                      DAG.getBuildVector(ShufVT, DL, V1Mask));
15899   if (V2InUse)
15900     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
15901                      DAG.getBuildVector(ShufVT, DL, V2Mask));
15902 
15903   // If we need shuffled inputs from both, blend the two.
15904   SDValue V;
15905   if (V1InUse && V2InUse)
15906     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
15907   else
15908     V = V1InUse ? V1 : V2;
15909 
15910   // Cast the result back to the correct type.
15911   return DAG.getBitcast(VT, V);
15912 }
15913 
15914 /// Generic lowering of 8-lane i16 shuffles.
15915 ///
15916 /// This handles both single-input shuffles and combined shuffle/blends with
15917 /// two inputs. The single input shuffles are immediately delegated to
15918 /// a dedicated lowering routine.
15919 ///
15920 /// The blends are lowered in one of three fundamental ways. If there are few
15921 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
15922 /// of the input is significantly cheaper when lowered as an interleaving of
15923 /// the two inputs, try to interleave them. Otherwise, blend the low and high
15924 /// halves of the inputs separately (making them have relatively few inputs)
15925 /// and then concatenate them.
15926 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15927                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15928                                  const X86Subtarget &Subtarget,
15929                                  SelectionDAG &DAG) {
15930   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
15931   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
15932   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15933 
15934   // Whenever we can lower this as a zext, that instruction is strictly faster
15935   // than any alternative.
15936   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
15937                                                    Zeroable, Subtarget, DAG))
15938     return ZExt;
15939 
15940   // Try to use lower using a truncation.
15941   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15942                                         Subtarget, DAG))
15943     return V;
15944 
15945   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
15946 
15947   if (NumV2Inputs == 0) {
15948     // Try to use shift instructions.
15949     if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
15950                                             Zeroable, Subtarget, DAG))
15951       return Shift;
15952 
15953     // Check for being able to broadcast a single element.
15954     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
15955                                                     Mask, Subtarget, DAG))
15956       return Broadcast;
15957 
15958     // Try to use bit rotation instructions.
15959     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
15960                                                  Subtarget, DAG))
15961       return Rotate;
15962 
15963     // Use dedicated unpack instructions for masks that match their pattern.
15964     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15965       return V;
15966 
15967     // Use dedicated pack instructions for masks that match their pattern.
15968     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15969                                          Subtarget))
15970       return V;
15971 
15972     // Try to use byte rotation instructions.
15973     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
15974                                                   Subtarget, DAG))
15975       return Rotate;
15976 
15977     // Make a copy of the mask so it can be modified.
15978     SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
15979     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
15980                                                Subtarget, DAG);
15981   }
15982 
15983   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
15984          "All single-input shuffles should be canonicalized to be V1-input "
15985          "shuffles.");
15986 
15987   // Try to use shift instructions.
15988   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
15989                                           Zeroable, Subtarget, DAG))
15990     return Shift;
15991 
15992   // See if we can use SSE4A Extraction / Insertion.
15993   if (Subtarget.hasSSE4A())
15994     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
15995                                           Zeroable, DAG))
15996       return V;
15997 
15998   // There are special ways we can lower some single-element blends.
15999   if (NumV2Inputs == 1)
16000     if (SDValue V = lowerShuffleAsElementInsertion(
16001             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16002       return V;
16003 
16004   // We have different paths for blend lowering, but they all must use the
16005   // *exact* same predicate.
16006   bool IsBlendSupported = Subtarget.hasSSE41();
16007   if (IsBlendSupported)
16008     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
16009                                             Zeroable, Subtarget, DAG))
16010       return Blend;
16011 
16012   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
16013                                              Zeroable, Subtarget, DAG))
16014     return Masked;
16015 
16016   // Use dedicated unpack instructions for masks that match their pattern.
16017   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
16018     return V;
16019 
16020   // Use dedicated pack instructions for masks that match their pattern.
16021   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
16022                                        Subtarget))
16023     return V;
16024 
16025   // Try to use lower using a truncation.
16026   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
16027                                        Subtarget, DAG))
16028     return V;
16029 
16030   // Try to use byte rotation instructions.
16031   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
16032                                                 Subtarget, DAG))
16033     return Rotate;
16034 
16035   if (SDValue BitBlend =
16036           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
16037     return BitBlend;
16038 
16039   // Try to use byte shift instructions to mask.
16040   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
16041                                               Zeroable, Subtarget, DAG))
16042     return V;
16043 
16044   // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
16045   // We could use SIGN_EXTEND_INREG+PACKSSDW for older targets but this seems to
16046   // be slower than a PSHUFLW+PSHUFHW+PSHUFD chain.
16047   int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
16048   if ((NumEvenDrops == 1 || NumEvenDrops == 2) && Subtarget.hasSSE41() &&
16049       !Subtarget.hasVLX()) {
16050     // Check if this is part of a 256-bit vector truncation.
16051     if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
16052         peekThroughBitcasts(V1).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16053         peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
16054       SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
16055       V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
16056                          getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
16057                          DAG.getTargetConstant(0xEE, DL, MVT::i8));
16058       V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
16059       V1 = extract128BitVector(V1V2, 0, DAG, DL);
16060       V2 = extract128BitVector(V1V2, 4, DAG, DL);
16061     } else {
16062       SmallVector<SDValue, 4> DWordClearOps(4,
16063                                             DAG.getConstant(0, DL, MVT::i32));
16064       for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
16065         DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
16066       SDValue DWordClearMask =
16067           DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
16068       V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
16069                        DWordClearMask);
16070       V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
16071                        DWordClearMask);
16072     }
16073     // Now pack things back together.
16074     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, V1, V2);
16075     if (NumEvenDrops == 2) {
16076       Result = DAG.getBitcast(MVT::v4i32, Result);
16077       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, Result, Result);
16078     }
16079     return Result;
16080   }
16081 
16082   // When compacting odd (upper) elements, use PACKSS pre-SSE41.
16083   int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
16084   if (NumOddDrops == 1) {
16085     bool HasSSE41 = Subtarget.hasSSE41();
16086     V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
16087                      DAG.getBitcast(MVT::v4i32, V1),
16088                      DAG.getTargetConstant(16, DL, MVT::i8));
16089     V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
16090                      DAG.getBitcast(MVT::v4i32, V2),
16091                      DAG.getTargetConstant(16, DL, MVT::i8));
16092     return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
16093                        MVT::v8i16, V1, V2);
16094   }
16095 
16096   // Try to lower by permuting the inputs into an unpack instruction.
16097   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
16098                                                       Mask, Subtarget, DAG))
16099     return Unpack;
16100 
16101   // If we can't directly blend but can use PSHUFB, that will be better as it
16102   // can both shuffle and set up the inefficient blend.
16103   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
16104     bool V1InUse, V2InUse;
16105     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
16106                                         Zeroable, DAG, V1InUse, V2InUse);
16107   }
16108 
16109   // We can always bit-blend if we have to so the fallback strategy is to
16110   // decompose into single-input permutes and blends/unpacks.
16111   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2,
16112                                               Mask, Subtarget, DAG);
16113 }
16114 
16115 /// Lower 8-lane 16-bit floating point shuffles.
16116 static SDValue lowerV8F16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16117                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16118                                  const X86Subtarget &Subtarget,
16119                                  SelectionDAG &DAG) {
16120   assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
16121   assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
16122   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16123   int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
16124 
16125   if (Subtarget.hasFP16()) {
16126     if (NumV2Elements == 0) {
16127       // Check for being able to broadcast a single element.
16128       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
16129                                                       Mask, Subtarget, DAG))
16130         return Broadcast;
16131     }
16132     if (NumV2Elements == 1 && Mask[0] >= 8)
16133       if (SDValue V = lowerShuffleAsElementInsertion(
16134               DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16135         return V;
16136   }
16137 
16138   V1 = DAG.getBitcast(MVT::v8i16, V1);
16139   V2 = DAG.getBitcast(MVT::v8i16, V2);
16140   return DAG.getBitcast(MVT::v8f16,
16141                         DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
16142 }
16143 
16144 // Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
16145 // sub-512-bit shuffles are padded to 512-bits for the shuffle and then
16146 // the active subvector is extracted.
16147 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
16148                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
16149                                      const X86Subtarget &Subtarget,
16150                                      SelectionDAG &DAG) {
16151   MVT MaskVT = VT.changeTypeToInteger();
16152   SDValue MaskNode;
16153   MVT ShuffleVT = VT;
16154   if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
16155     V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
16156     V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
16157     ShuffleVT = V1.getSimpleValueType();
16158 
16159     // Adjust mask to correct indices for the second input.
16160     int NumElts = VT.getVectorNumElements();
16161     unsigned Scale = 512 / VT.getSizeInBits();
16162     SmallVector<int, 32> AdjustedMask(Mask.begin(), Mask.end());
16163     for (int &M : AdjustedMask)
16164       if (NumElts <= M)
16165         M += (Scale - 1) * NumElts;
16166     MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
16167     MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
16168   } else {
16169     MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
16170   }
16171 
16172   SDValue Result;
16173   if (V2.isUndef())
16174     Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
16175   else
16176     Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
16177 
16178   if (VT != ShuffleVT)
16179     Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
16180 
16181   return Result;
16182 }
16183 
16184 /// Generic lowering of v16i8 shuffles.
16185 ///
16186 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
16187 /// detect any complexity reducing interleaving. If that doesn't help, it uses
16188 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
16189 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
16190 /// back together.
16191 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16192                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16193                                  const X86Subtarget &Subtarget,
16194                                  SelectionDAG &DAG) {
16195   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
16196   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
16197   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16198 
16199   // Try to use shift instructions.
16200   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
16201                                           Zeroable, Subtarget, DAG))
16202     return Shift;
16203 
16204   // Try to use byte rotation instructions.
16205   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
16206                                                 Subtarget, DAG))
16207     return Rotate;
16208 
16209   // Use dedicated pack instructions for masks that match their pattern.
16210   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
16211                                        Subtarget))
16212     return V;
16213 
16214   // Try to use a zext lowering.
16215   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
16216                                                    Zeroable, Subtarget, DAG))
16217     return ZExt;
16218 
16219   // Try to use lower using a truncation.
16220   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
16221                                         Subtarget, DAG))
16222     return V;
16223 
16224   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
16225                                        Subtarget, DAG))
16226     return V;
16227 
16228   // See if we can use SSE4A Extraction / Insertion.
16229   if (Subtarget.hasSSE4A())
16230     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
16231                                           Zeroable, DAG))
16232       return V;
16233 
16234   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
16235 
16236   // For single-input shuffles, there are some nicer lowering tricks we can use.
16237   if (NumV2Elements == 0) {
16238     // Check for being able to broadcast a single element.
16239     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
16240                                                     Mask, Subtarget, DAG))
16241       return Broadcast;
16242 
16243     // Try to use bit rotation instructions.
16244     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
16245                                                  Subtarget, DAG))
16246       return Rotate;
16247 
16248     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
16249       return V;
16250 
16251     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
16252     // Notably, this handles splat and partial-splat shuffles more efficiently.
16253     // However, it only makes sense if the pre-duplication shuffle simplifies
16254     // things significantly. Currently, this means we need to be able to
16255     // express the pre-duplication shuffle as an i16 shuffle.
16256     //
16257     // FIXME: We should check for other patterns which can be widened into an
16258     // i16 shuffle as well.
16259     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
16260       for (int i = 0; i < 16; i += 2)
16261         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
16262           return false;
16263 
16264       return true;
16265     };
16266     auto tryToWidenViaDuplication = [&]() -> SDValue {
16267       if (!canWidenViaDuplication(Mask))
16268         return SDValue();
16269       SmallVector<int, 4> LoInputs;
16270       copy_if(Mask, std::back_inserter(LoInputs),
16271               [](int M) { return M >= 0 && M < 8; });
16272       array_pod_sort(LoInputs.begin(), LoInputs.end());
16273       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
16274                      LoInputs.end());
16275       SmallVector<int, 4> HiInputs;
16276       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
16277       array_pod_sort(HiInputs.begin(), HiInputs.end());
16278       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
16279                      HiInputs.end());
16280 
16281       bool TargetLo = LoInputs.size() >= HiInputs.size();
16282       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
16283       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
16284 
16285       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
16286       SmallDenseMap<int, int, 8> LaneMap;
16287       for (int I : InPlaceInputs) {
16288         PreDupI16Shuffle[I/2] = I/2;
16289         LaneMap[I] = I;
16290       }
16291       int j = TargetLo ? 0 : 4, je = j + 4;
16292       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
16293         // Check if j is already a shuffle of this input. This happens when
16294         // there are two adjacent bytes after we move the low one.
16295         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
16296           // If we haven't yet mapped the input, search for a slot into which
16297           // we can map it.
16298           while (j < je && PreDupI16Shuffle[j] >= 0)
16299             ++j;
16300 
16301           if (j == je)
16302             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
16303             return SDValue();
16304 
16305           // Map this input with the i16 shuffle.
16306           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
16307         }
16308 
16309         // Update the lane map based on the mapping we ended up with.
16310         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
16311       }
16312       V1 = DAG.getBitcast(
16313           MVT::v16i8,
16314           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
16315                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
16316 
16317       // Unpack the bytes to form the i16s that will be shuffled into place.
16318       bool EvenInUse = false, OddInUse = false;
16319       for (int i = 0; i < 16; i += 2) {
16320         EvenInUse |= (Mask[i + 0] >= 0);
16321         OddInUse |= (Mask[i + 1] >= 0);
16322         if (EvenInUse && OddInUse)
16323           break;
16324       }
16325       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
16326                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
16327                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
16328 
16329       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
16330       for (int i = 0; i < 16; ++i)
16331         if (Mask[i] >= 0) {
16332           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
16333           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
16334           if (PostDupI16Shuffle[i / 2] < 0)
16335             PostDupI16Shuffle[i / 2] = MappedMask;
16336           else
16337             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
16338                    "Conflicting entries in the original shuffle!");
16339         }
16340       return DAG.getBitcast(
16341           MVT::v16i8,
16342           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
16343                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
16344     };
16345     if (SDValue V = tryToWidenViaDuplication())
16346       return V;
16347   }
16348 
16349   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
16350                                              Zeroable, Subtarget, DAG))
16351     return Masked;
16352 
16353   // Use dedicated unpack instructions for masks that match their pattern.
16354   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
16355     return V;
16356 
16357   // Try to use byte shift instructions to mask.
16358   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
16359                                               Zeroable, Subtarget, DAG))
16360     return V;
16361 
16362   // Check for compaction patterns.
16363   bool IsSingleInput = V2.isUndef();
16364   int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
16365 
16366   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
16367   // with PSHUFB. It is important to do this before we attempt to generate any
16368   // blends but after all of the single-input lowerings. If the single input
16369   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
16370   // want to preserve that and we can DAG combine any longer sequences into
16371   // a PSHUFB in the end. But once we start blending from multiple inputs,
16372   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
16373   // and there are *very* few patterns that would actually be faster than the
16374   // PSHUFB approach because of its ability to zero lanes.
16375   //
16376   // If the mask is a binary compaction, we can more efficiently perform this
16377   // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
16378   //
16379   // FIXME: The only exceptions to the above are blends which are exact
16380   // interleavings with direct instructions supporting them. We currently don't
16381   // handle those well here.
16382   if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
16383     bool V1InUse = false;
16384     bool V2InUse = false;
16385 
16386     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
16387         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
16388 
16389     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
16390     // do so. This avoids using them to handle blends-with-zero which is
16391     // important as a single pshufb is significantly faster for that.
16392     if (V1InUse && V2InUse) {
16393       if (Subtarget.hasSSE41())
16394         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
16395                                                 Zeroable, Subtarget, DAG))
16396           return Blend;
16397 
16398       // We can use an unpack to do the blending rather than an or in some
16399       // cases. Even though the or may be (very minorly) more efficient, we
16400       // preference this lowering because there are common cases where part of
16401       // the complexity of the shuffles goes away when we do the final blend as
16402       // an unpack.
16403       // FIXME: It might be worth trying to detect if the unpack-feeding
16404       // shuffles will both be pshufb, in which case we shouldn't bother with
16405       // this.
16406       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
16407               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
16408         return Unpack;
16409 
16410       // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
16411       if (Subtarget.hasVBMI())
16412         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
16413                                      DAG);
16414 
16415       // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
16416       if (Subtarget.hasXOP()) {
16417         SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
16418         return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
16419       }
16420 
16421       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
16422       // PALIGNR will be cheaper than the second PSHUFB+OR.
16423       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
16424               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
16425         return V;
16426     }
16427 
16428     return PSHUFB;
16429   }
16430 
16431   // There are special ways we can lower some single-element blends.
16432   if (NumV2Elements == 1)
16433     if (SDValue V = lowerShuffleAsElementInsertion(
16434             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
16435       return V;
16436 
16437   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
16438     return Blend;
16439 
16440   // Check whether a compaction lowering can be done. This handles shuffles
16441   // which take every Nth element for some even N. See the helper function for
16442   // details.
16443   //
16444   // We special case these as they can be particularly efficiently handled with
16445   // the PACKUSB instruction on x86 and they show up in common patterns of
16446   // rearranging bytes to truncate wide elements.
16447   if (NumEvenDrops) {
16448     // NumEvenDrops is the power of two stride of the elements. Another way of
16449     // thinking about it is that we need to drop the even elements this many
16450     // times to get the original input.
16451 
16452     // First we need to zero all the dropped bytes.
16453     assert(NumEvenDrops <= 3 &&
16454            "No support for dropping even elements more than 3 times.");
16455     SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
16456     for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
16457       WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
16458     SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
16459     V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
16460                      WordClearMask);
16461     if (!IsSingleInput)
16462       V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
16463                        WordClearMask);
16464 
16465     // Now pack things back together.
16466     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
16467                                  IsSingleInput ? V1 : V2);
16468     for (int i = 1; i < NumEvenDrops; ++i) {
16469       Result = DAG.getBitcast(MVT::v8i16, Result);
16470       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
16471     }
16472     return Result;
16473   }
16474 
16475   int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
16476   if (NumOddDrops == 1) {
16477     V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
16478                      DAG.getBitcast(MVT::v8i16, V1),
16479                      DAG.getTargetConstant(8, DL, MVT::i8));
16480     if (!IsSingleInput)
16481       V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
16482                        DAG.getBitcast(MVT::v8i16, V2),
16483                        DAG.getTargetConstant(8, DL, MVT::i8));
16484     return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
16485                        IsSingleInput ? V1 : V2);
16486   }
16487 
16488   // Handle multi-input cases by blending/unpacking single-input shuffles.
16489   if (NumV2Elements > 0)
16490     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
16491                                                 Subtarget, DAG);
16492 
16493   // The fallback path for single-input shuffles widens this into two v8i16
16494   // vectors with unpacks, shuffles those, and then pulls them back together
16495   // with a pack.
16496   SDValue V = V1;
16497 
16498   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
16499   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
16500   for (int i = 0; i < 16; ++i)
16501     if (Mask[i] >= 0)
16502       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
16503 
16504   SDValue VLoHalf, VHiHalf;
16505   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
16506   // them out and avoid using UNPCK{L,H} to extract the elements of V as
16507   // i16s.
16508   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
16509       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
16510     // Use a mask to drop the high bytes.
16511     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
16512     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
16513                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
16514 
16515     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
16516     VHiHalf = DAG.getUNDEF(MVT::v8i16);
16517 
16518     // Squash the masks to point directly into VLoHalf.
16519     for (int &M : LoBlendMask)
16520       if (M >= 0)
16521         M /= 2;
16522     for (int &M : HiBlendMask)
16523       if (M >= 0)
16524         M /= 2;
16525   } else {
16526     // Otherwise just unpack the low half of V into VLoHalf and the high half into
16527     // VHiHalf so that we can blend them as i16s.
16528     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
16529 
16530     VLoHalf = DAG.getBitcast(
16531         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
16532     VHiHalf = DAG.getBitcast(
16533         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
16534   }
16535 
16536   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
16537   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
16538 
16539   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
16540 }
16541 
16542 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
16543 ///
16544 /// This routine breaks down the specific type of 128-bit shuffle and
16545 /// dispatches to the lowering routines accordingly.
16546 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
16547                                   MVT VT, SDValue V1, SDValue V2,
16548                                   const APInt &Zeroable,
16549                                   const X86Subtarget &Subtarget,
16550                                   SelectionDAG &DAG) {
16551   switch (VT.SimpleTy) {
16552   case MVT::v2i64:
16553     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16554   case MVT::v2f64:
16555     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16556   case MVT::v4i32:
16557     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16558   case MVT::v4f32:
16559     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16560   case MVT::v8i16:
16561     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16562   case MVT::v8f16:
16563     return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16564   case MVT::v16i8:
16565     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16566 
16567   default:
16568     llvm_unreachable("Unimplemented!");
16569   }
16570 }
16571 
16572 /// Generic routine to split vector shuffle into half-sized shuffles.
16573 ///
16574 /// This routine just extracts two subvectors, shuffles them independently, and
16575 /// then concatenates them back together. This should work effectively with all
16576 /// AVX vector shuffle types.
16577 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
16578                                     SDValue V2, ArrayRef<int> Mask,
16579                                     SelectionDAG &DAG) {
16580   assert(VT.getSizeInBits() >= 256 &&
16581          "Only for 256-bit or wider vector shuffles!");
16582   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
16583   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
16584 
16585   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
16586   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
16587 
16588   int NumElements = VT.getVectorNumElements();
16589   int SplitNumElements = NumElements / 2;
16590   MVT ScalarVT = VT.getVectorElementType();
16591   MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
16592 
16593   // Use splitVector/extractSubVector so that split build-vectors just build two
16594   // narrower build vectors. This helps shuffling with splats and zeros.
16595   auto SplitVector = [&](SDValue V) {
16596     SDValue LoV, HiV;
16597     std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
16598     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
16599                           DAG.getBitcast(SplitVT, HiV));
16600   };
16601 
16602   SDValue LoV1, HiV1, LoV2, HiV2;
16603   std::tie(LoV1, HiV1) = SplitVector(V1);
16604   std::tie(LoV2, HiV2) = SplitVector(V2);
16605 
16606   // Now create two 4-way blends of these half-width vectors.
16607   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
16608     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
16609     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
16610     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
16611     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
16612     for (int i = 0; i < SplitNumElements; ++i) {
16613       int M = HalfMask[i];
16614       if (M >= NumElements) {
16615         if (M >= NumElements + SplitNumElements)
16616           UseHiV2 = true;
16617         else
16618           UseLoV2 = true;
16619         V2BlendMask[i] = M - NumElements;
16620         BlendMask[i] = SplitNumElements + i;
16621       } else if (M >= 0) {
16622         if (M >= SplitNumElements)
16623           UseHiV1 = true;
16624         else
16625           UseLoV1 = true;
16626         V1BlendMask[i] = M;
16627         BlendMask[i] = i;
16628       }
16629     }
16630 
16631     // Because the lowering happens after all combining takes place, we need to
16632     // manually combine these blend masks as much as possible so that we create
16633     // a minimal number of high-level vector shuffle nodes.
16634 
16635     // First try just blending the halves of V1 or V2.
16636     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
16637       return DAG.getUNDEF(SplitVT);
16638     if (!UseLoV2 && !UseHiV2)
16639       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
16640     if (!UseLoV1 && !UseHiV1)
16641       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
16642 
16643     SDValue V1Blend, V2Blend;
16644     if (UseLoV1 && UseHiV1) {
16645       V1Blend =
16646         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
16647     } else {
16648       // We only use half of V1 so map the usage down into the final blend mask.
16649       V1Blend = UseLoV1 ? LoV1 : HiV1;
16650       for (int i = 0; i < SplitNumElements; ++i)
16651         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
16652           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
16653     }
16654     if (UseLoV2 && UseHiV2) {
16655       V2Blend =
16656         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
16657     } else {
16658       // We only use half of V2 so map the usage down into the final blend mask.
16659       V2Blend = UseLoV2 ? LoV2 : HiV2;
16660       for (int i = 0; i < SplitNumElements; ++i)
16661         if (BlendMask[i] >= SplitNumElements)
16662           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
16663     }
16664     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
16665   };
16666   SDValue Lo = HalfBlend(LoMask);
16667   SDValue Hi = HalfBlend(HiMask);
16668   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
16669 }
16670 
16671 /// Either split a vector in halves or decompose the shuffles and the
16672 /// blend/unpack.
16673 ///
16674 /// This is provided as a good fallback for many lowerings of non-single-input
16675 /// shuffles with more than one 128-bit lane. In those cases, we want to select
16676 /// between splitting the shuffle into 128-bit components and stitching those
16677 /// back together vs. extracting the single-input shuffles and blending those
16678 /// results.
16679 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
16680                                           SDValue V2, ArrayRef<int> Mask,
16681                                           const X86Subtarget &Subtarget,
16682                                           SelectionDAG &DAG) {
16683   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
16684          "shuffles as it could then recurse on itself.");
16685   int Size = Mask.size();
16686 
16687   // If this can be modeled as a broadcast of two elements followed by a blend,
16688   // prefer that lowering. This is especially important because broadcasts can
16689   // often fold with memory operands.
16690   auto DoBothBroadcast = [&] {
16691     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
16692     for (int M : Mask)
16693       if (M >= Size) {
16694         if (V2BroadcastIdx < 0)
16695           V2BroadcastIdx = M - Size;
16696         else if (M - Size != V2BroadcastIdx)
16697           return false;
16698       } else if (M >= 0) {
16699         if (V1BroadcastIdx < 0)
16700           V1BroadcastIdx = M;
16701         else if (M != V1BroadcastIdx)
16702           return false;
16703       }
16704     return true;
16705   };
16706   if (DoBothBroadcast())
16707     return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
16708                                                 DAG);
16709 
16710   // If the inputs all stem from a single 128-bit lane of each input, then we
16711   // split them rather than blending because the split will decompose to
16712   // unusually few instructions.
16713   int LaneCount = VT.getSizeInBits() / 128;
16714   int LaneSize = Size / LaneCount;
16715   SmallBitVector LaneInputs[2];
16716   LaneInputs[0].resize(LaneCount, false);
16717   LaneInputs[1].resize(LaneCount, false);
16718   for (int i = 0; i < Size; ++i)
16719     if (Mask[i] >= 0)
16720       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
16721   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
16722     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16723 
16724   // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
16725   // requires that the decomposed single-input shuffles don't end up here.
16726   return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
16727                                               DAG);
16728 }
16729 
16730 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16731 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
16732 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
16733                                                  SDValue V1, SDValue V2,
16734                                                  ArrayRef<int> Mask,
16735                                                  SelectionDAG &DAG) {
16736   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
16737 
16738   int LHSMask[4] = {-1, -1, -1, -1};
16739   int RHSMask[4] = {-1, -1, -1, -1};
16740   unsigned SHUFPMask = 0;
16741 
16742   // As SHUFPD uses a single LHS/RHS element per lane, we can always
16743   // perform the shuffle once the lanes have been shuffled in place.
16744   for (int i = 0; i != 4; ++i) {
16745     int M = Mask[i];
16746     if (M < 0)
16747       continue;
16748     int LaneBase = i & ~1;
16749     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
16750     LaneMask[LaneBase + (M & 1)] = M;
16751     SHUFPMask |= (M & 1) << i;
16752   }
16753 
16754   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
16755   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
16756   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
16757                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
16758 }
16759 
16760 /// Lower a vector shuffle crossing multiple 128-bit lanes as
16761 /// a lane permutation followed by a per-lane permutation.
16762 ///
16763 /// This is mainly for cases where we can have non-repeating permutes
16764 /// in each lane.
16765 ///
16766 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
16767 /// we should investigate merging them.
16768 static SDValue lowerShuffleAsLanePermuteAndPermute(
16769     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16770     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
16771   int NumElts = VT.getVectorNumElements();
16772   int NumLanes = VT.getSizeInBits() / 128;
16773   int NumEltsPerLane = NumElts / NumLanes;
16774   bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
16775 
16776   /// Attempts to find a sublane permute with the given size
16777   /// that gets all elements into their target lanes.
16778   ///
16779   /// If successful, fills CrossLaneMask and InLaneMask and returns true.
16780   /// If unsuccessful, returns false and may overwrite InLaneMask.
16781   auto getSublanePermute = [&](int NumSublanes) -> SDValue {
16782     int NumSublanesPerLane = NumSublanes / NumLanes;
16783     int NumEltsPerSublane = NumElts / NumSublanes;
16784 
16785     SmallVector<int, 16> CrossLaneMask;
16786     SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
16787     // CrossLaneMask but one entry == one sublane.
16788     SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
16789 
16790     for (int i = 0; i != NumElts; ++i) {
16791       int M = Mask[i];
16792       if (M < 0)
16793         continue;
16794 
16795       int SrcSublane = M / NumEltsPerSublane;
16796       int DstLane = i / NumEltsPerLane;
16797 
16798       // We only need to get the elements into the right lane, not sublane.
16799       // So search all sublanes that make up the destination lane.
16800       bool Found = false;
16801       int DstSubStart = DstLane * NumSublanesPerLane;
16802       int DstSubEnd = DstSubStart + NumSublanesPerLane;
16803       for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
16804         if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
16805           continue;
16806 
16807         Found = true;
16808         CrossLaneMaskLarge[DstSublane] = SrcSublane;
16809         int DstSublaneOffset = DstSublane * NumEltsPerSublane;
16810         InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
16811         break;
16812       }
16813       if (!Found)
16814         return SDValue();
16815     }
16816 
16817     // Fill CrossLaneMask using CrossLaneMaskLarge.
16818     narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
16819 
16820     if (!CanUseSublanes) {
16821       // If we're only shuffling a single lowest lane and the rest are identity
16822       // then don't bother.
16823       // TODO - isShuffleMaskInputInPlace could be extended to something like
16824       // this.
16825       int NumIdentityLanes = 0;
16826       bool OnlyShuffleLowestLane = true;
16827       for (int i = 0; i != NumLanes; ++i) {
16828         int LaneOffset = i * NumEltsPerLane;
16829         if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
16830                                        i * NumEltsPerLane))
16831           NumIdentityLanes++;
16832         else if (CrossLaneMask[LaneOffset] != 0)
16833           OnlyShuffleLowestLane = false;
16834       }
16835       if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
16836         return SDValue();
16837     }
16838 
16839     SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
16840     return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
16841                                 InLaneMask);
16842   };
16843 
16844   // First attempt a solution with full lanes.
16845   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
16846     return V;
16847 
16848   // The rest of the solutions use sublanes.
16849   if (!CanUseSublanes)
16850     return SDValue();
16851 
16852   // Then attempt a solution with 64-bit sublanes (vpermq).
16853   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
16854     return V;
16855 
16856   // If that doesn't work and we have fast variable cross-lane shuffle,
16857   // attempt 32-bit sublanes (vpermd).
16858   if (!Subtarget.hasFastVariableCrossLaneShuffle())
16859     return SDValue();
16860 
16861   return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
16862 }
16863 
16864 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
16865 /// source with a lane permutation.
16866 ///
16867 /// This lowering strategy results in four instructions in the worst case for a
16868 /// single-input cross lane shuffle which is lower than any other fully general
16869 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
16870 /// shuffle pattern should be handled prior to trying this lowering.
16871 static SDValue lowerShuffleAsLanePermuteAndShuffle(
16872     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16873     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
16874   // FIXME: This should probably be generalized for 512-bit vectors as well.
16875   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
16876   int Size = Mask.size();
16877   int LaneSize = Size / 2;
16878 
16879   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16880   // Only do this if the elements aren't all from the lower lane,
16881   // otherwise we're (probably) better off doing a split.
16882   if (VT == MVT::v4f64 &&
16883       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
16884     return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
16885 
16886   // If there are only inputs from one 128-bit lane, splitting will in fact be
16887   // less expensive. The flags track whether the given lane contains an element
16888   // that crosses to another lane.
16889   bool AllLanes;
16890   if (!Subtarget.hasAVX2()) {
16891     bool LaneCrossing[2] = {false, false};
16892     for (int i = 0; i < Size; ++i)
16893       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
16894         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
16895     AllLanes = LaneCrossing[0] && LaneCrossing[1];
16896   } else {
16897     bool LaneUsed[2] = {false, false};
16898     for (int i = 0; i < Size; ++i)
16899       if (Mask[i] >= 0)
16900         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
16901     AllLanes = LaneUsed[0] && LaneUsed[1];
16902   }
16903 
16904   // TODO - we could support shuffling V2 in the Flipped input.
16905   assert(V2.isUndef() &&
16906          "This last part of this routine only works on single input shuffles");
16907 
16908   SmallVector<int, 32> InLaneMask(Mask.begin(), Mask.end());
16909   for (int i = 0; i < Size; ++i) {
16910     int &M = InLaneMask[i];
16911     if (M < 0)
16912       continue;
16913     if (((M % Size) / LaneSize) != (i / LaneSize))
16914       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
16915   }
16916   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
16917          "In-lane shuffle mask expected");
16918 
16919   // If we're not using both lanes in each lane and the inlane mask is not
16920   // repeating, then we're better off splitting.
16921   if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
16922     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16923 
16924   // Flip the lanes, and shuffle the results which should now be in-lane.
16925   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
16926   SDValue Flipped = DAG.getBitcast(PVT, V1);
16927   Flipped =
16928       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
16929   Flipped = DAG.getBitcast(VT, Flipped);
16930   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
16931 }
16932 
16933 /// Handle lowering 2-lane 128-bit shuffles.
16934 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
16935                                   SDValue V2, ArrayRef<int> Mask,
16936                                   const APInt &Zeroable,
16937                                   const X86Subtarget &Subtarget,
16938                                   SelectionDAG &DAG) {
16939   if (V2.isUndef()) {
16940     // Attempt to match VBROADCAST*128 subvector broadcast load.
16941     bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
16942     bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
16943     if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
16944         X86::mayFoldLoad(peekThroughOneUseBitcasts(V1), Subtarget)) {
16945       MVT MemVT = VT.getHalfNumVectorElementsVT();
16946       unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
16947       auto *Ld = cast<LoadSDNode>(peekThroughOneUseBitcasts(V1));
16948       if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
16949                                              VT, MemVT, Ld, Ofs, DAG))
16950         return BcstLd;
16951     }
16952 
16953     // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
16954     if (Subtarget.hasAVX2())
16955       return SDValue();
16956   }
16957 
16958   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
16959 
16960   SmallVector<int, 4> WidenedMask;
16961   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
16962     return SDValue();
16963 
16964   bool IsLowZero = (Zeroable & 0x3) == 0x3;
16965   bool IsHighZero = (Zeroable & 0xc) == 0xc;
16966 
16967   // Try to use an insert into a zero vector.
16968   if (WidenedMask[0] == 0 && IsHighZero) {
16969     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16970     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
16971                               DAG.getIntPtrConstant(0, DL));
16972     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16973                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
16974                        DAG.getIntPtrConstant(0, DL));
16975   }
16976 
16977   // TODO: If minimizing size and one of the inputs is a zero vector and the
16978   // the zero vector has only one use, we could use a VPERM2X128 to save the
16979   // instruction bytes needed to explicitly generate the zero vector.
16980 
16981   // Blends are faster and handle all the non-lane-crossing cases.
16982   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
16983                                           Subtarget, DAG))
16984     return Blend;
16985 
16986   // If either input operand is a zero vector, use VPERM2X128 because its mask
16987   // allows us to replace the zero input with an implicit zero.
16988   if (!IsLowZero && !IsHighZero) {
16989     // Check for patterns which can be matched with a single insert of a 128-bit
16990     // subvector.
16991     bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
16992     if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
16993 
16994       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
16995       // this will likely become vinsertf128 which can't fold a 256-bit memop.
16996       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
16997         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16998         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
16999                                      OnlyUsesV1 ? V1 : V2,
17000                                      DAG.getIntPtrConstant(0, DL));
17001         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17002                            DAG.getIntPtrConstant(2, DL));
17003       }
17004     }
17005 
17006     // Try to use SHUF128 if possible.
17007     if (Subtarget.hasVLX()) {
17008       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
17009         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
17010                             ((WidenedMask[1] % 2) << 1);
17011         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
17012                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
17013       }
17014     }
17015   }
17016 
17017   // Otherwise form a 128-bit permutation. After accounting for undefs,
17018   // convert the 64-bit shuffle mask selection values into 128-bit
17019   // selection bits by dividing the indexes by 2 and shifting into positions
17020   // defined by a vperm2*128 instruction's immediate control byte.
17021 
17022   // The immediate permute control byte looks like this:
17023   //    [1:0] - select 128 bits from sources for low half of destination
17024   //    [2]   - ignore
17025   //    [3]   - zero low half of destination
17026   //    [5:4] - select 128 bits from sources for high half of destination
17027   //    [6]   - ignore
17028   //    [7]   - zero high half of destination
17029 
17030   assert((WidenedMask[0] >= 0 || IsLowZero) &&
17031          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
17032 
17033   unsigned PermMask = 0;
17034   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
17035   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
17036 
17037   // Check the immediate mask and replace unused sources with undef.
17038   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
17039     V1 = DAG.getUNDEF(VT);
17040   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
17041     V2 = DAG.getUNDEF(VT);
17042 
17043   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
17044                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
17045 }
17046 
17047 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
17048 /// shuffling each lane.
17049 ///
17050 /// This attempts to create a repeated lane shuffle where each lane uses one
17051 /// or two of the lanes of the inputs. The lanes of the input vectors are
17052 /// shuffled in one or two independent shuffles to get the lanes into the
17053 /// position needed by the final shuffle.
17054 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
17055     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
17056     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
17057   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
17058 
17059   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
17060     return SDValue();
17061 
17062   int NumElts = Mask.size();
17063   int NumLanes = VT.getSizeInBits() / 128;
17064   int NumLaneElts = 128 / VT.getScalarSizeInBits();
17065   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
17066   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
17067 
17068   // First pass will try to fill in the RepeatMask from lanes that need two
17069   // sources.
17070   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17071     int Srcs[2] = {-1, -1};
17072     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
17073     for (int i = 0; i != NumLaneElts; ++i) {
17074       int M = Mask[(Lane * NumLaneElts) + i];
17075       if (M < 0)
17076         continue;
17077       // Determine which of the possible input lanes (NumLanes from each source)
17078       // this element comes from. Assign that as one of the sources for this
17079       // lane. We can assign up to 2 sources for this lane. If we run out
17080       // sources we can't do anything.
17081       int LaneSrc = M / NumLaneElts;
17082       int Src;
17083       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
17084         Src = 0;
17085       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
17086         Src = 1;
17087       else
17088         return SDValue();
17089 
17090       Srcs[Src] = LaneSrc;
17091       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
17092     }
17093 
17094     // If this lane has two sources, see if it fits with the repeat mask so far.
17095     if (Srcs[1] < 0)
17096       continue;
17097 
17098     LaneSrcs[Lane][0] = Srcs[0];
17099     LaneSrcs[Lane][1] = Srcs[1];
17100 
17101     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
17102       assert(M1.size() == M2.size() && "Unexpected mask size");
17103       for (int i = 0, e = M1.size(); i != e; ++i)
17104         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
17105           return false;
17106       return true;
17107     };
17108 
17109     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
17110       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
17111       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
17112         int M = Mask[i];
17113         if (M < 0)
17114           continue;
17115         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
17116                "Unexpected mask element");
17117         MergedMask[i] = M;
17118       }
17119     };
17120 
17121     if (MatchMasks(InLaneMask, RepeatMask)) {
17122       // Merge this lane mask into the final repeat mask.
17123       MergeMasks(InLaneMask, RepeatMask);
17124       continue;
17125     }
17126 
17127     // Didn't find a match. Swap the operands and try again.
17128     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
17129     ShuffleVectorSDNode::commuteMask(InLaneMask);
17130 
17131     if (MatchMasks(InLaneMask, RepeatMask)) {
17132       // Merge this lane mask into the final repeat mask.
17133       MergeMasks(InLaneMask, RepeatMask);
17134       continue;
17135     }
17136 
17137     // Couldn't find a match with the operands in either order.
17138     return SDValue();
17139   }
17140 
17141   // Now handle any lanes with only one source.
17142   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17143     // If this lane has already been processed, skip it.
17144     if (LaneSrcs[Lane][0] >= 0)
17145       continue;
17146 
17147     for (int i = 0; i != NumLaneElts; ++i) {
17148       int M = Mask[(Lane * NumLaneElts) + i];
17149       if (M < 0)
17150         continue;
17151 
17152       // If RepeatMask isn't defined yet we can define it ourself.
17153       if (RepeatMask[i] < 0)
17154         RepeatMask[i] = M % NumLaneElts;
17155 
17156       if (RepeatMask[i] < NumElts) {
17157         if (RepeatMask[i] != M % NumLaneElts)
17158           return SDValue();
17159         LaneSrcs[Lane][0] = M / NumLaneElts;
17160       } else {
17161         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
17162           return SDValue();
17163         LaneSrcs[Lane][1] = M / NumLaneElts;
17164       }
17165     }
17166 
17167     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
17168       return SDValue();
17169   }
17170 
17171   SmallVector<int, 16> NewMask(NumElts, -1);
17172   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17173     int Src = LaneSrcs[Lane][0];
17174     for (int i = 0; i != NumLaneElts; ++i) {
17175       int M = -1;
17176       if (Src >= 0)
17177         M = Src * NumLaneElts + i;
17178       NewMask[Lane * NumLaneElts + i] = M;
17179     }
17180   }
17181   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17182   // Ensure we didn't get back the shuffle we started with.
17183   // FIXME: This is a hack to make up for some splat handling code in
17184   // getVectorShuffle.
17185   if (isa<ShuffleVectorSDNode>(NewV1) &&
17186       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
17187     return SDValue();
17188 
17189   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17190     int Src = LaneSrcs[Lane][1];
17191     for (int i = 0; i != NumLaneElts; ++i) {
17192       int M = -1;
17193       if (Src >= 0)
17194         M = Src * NumLaneElts + i;
17195       NewMask[Lane * NumLaneElts + i] = M;
17196     }
17197   }
17198   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17199   // Ensure we didn't get back the shuffle we started with.
17200   // FIXME: This is a hack to make up for some splat handling code in
17201   // getVectorShuffle.
17202   if (isa<ShuffleVectorSDNode>(NewV2) &&
17203       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
17204     return SDValue();
17205 
17206   for (int i = 0; i != NumElts; ++i) {
17207     NewMask[i] = RepeatMask[i % NumLaneElts];
17208     if (NewMask[i] < 0)
17209       continue;
17210 
17211     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
17212   }
17213   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
17214 }
17215 
17216 /// If the input shuffle mask results in a vector that is undefined in all upper
17217 /// or lower half elements and that mask accesses only 2 halves of the
17218 /// shuffle's operands, return true. A mask of half the width with mask indexes
17219 /// adjusted to access the extracted halves of the original shuffle operands is
17220 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
17221 /// lower half of each input operand is accessed.
17222 static bool
17223 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
17224                    int &HalfIdx1, int &HalfIdx2) {
17225   assert((Mask.size() == HalfMask.size() * 2) &&
17226          "Expected input mask to be twice as long as output");
17227 
17228   // Exactly one half of the result must be undef to allow narrowing.
17229   bool UndefLower = isUndefLowerHalf(Mask);
17230   bool UndefUpper = isUndefUpperHalf(Mask);
17231   if (UndefLower == UndefUpper)
17232     return false;
17233 
17234   unsigned HalfNumElts = HalfMask.size();
17235   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
17236   HalfIdx1 = -1;
17237   HalfIdx2 = -1;
17238   for (unsigned i = 0; i != HalfNumElts; ++i) {
17239     int M = Mask[i + MaskIndexOffset];
17240     if (M < 0) {
17241       HalfMask[i] = M;
17242       continue;
17243     }
17244 
17245     // Determine which of the 4 half vectors this element is from.
17246     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
17247     int HalfIdx = M / HalfNumElts;
17248 
17249     // Determine the element index into its half vector source.
17250     int HalfElt = M % HalfNumElts;
17251 
17252     // We can shuffle with up to 2 half vectors, set the new 'half'
17253     // shuffle mask accordingly.
17254     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
17255       HalfMask[i] = HalfElt;
17256       HalfIdx1 = HalfIdx;
17257       continue;
17258     }
17259     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
17260       HalfMask[i] = HalfElt + HalfNumElts;
17261       HalfIdx2 = HalfIdx;
17262       continue;
17263     }
17264 
17265     // Too many half vectors referenced.
17266     return false;
17267   }
17268 
17269   return true;
17270 }
17271 
17272 /// Given the output values from getHalfShuffleMask(), create a half width
17273 /// shuffle of extracted vectors followed by an insert back to full width.
17274 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
17275                                      ArrayRef<int> HalfMask, int HalfIdx1,
17276                                      int HalfIdx2, bool UndefLower,
17277                                      SelectionDAG &DAG, bool UseConcat = false) {
17278   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
17279   assert(V1.getValueType().isSimple() && "Expecting only simple types");
17280 
17281   MVT VT = V1.getSimpleValueType();
17282   MVT HalfVT = VT.getHalfNumVectorElementsVT();
17283   unsigned HalfNumElts = HalfVT.getVectorNumElements();
17284 
17285   auto getHalfVector = [&](int HalfIdx) {
17286     if (HalfIdx < 0)
17287       return DAG.getUNDEF(HalfVT);
17288     SDValue V = (HalfIdx < 2 ? V1 : V2);
17289     HalfIdx = (HalfIdx % 2) * HalfNumElts;
17290     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
17291                        DAG.getIntPtrConstant(HalfIdx, DL));
17292   };
17293 
17294   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
17295   SDValue Half1 = getHalfVector(HalfIdx1);
17296   SDValue Half2 = getHalfVector(HalfIdx2);
17297   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
17298   if (UseConcat) {
17299     SDValue Op0 = V;
17300     SDValue Op1 = DAG.getUNDEF(HalfVT);
17301     if (UndefLower)
17302       std::swap(Op0, Op1);
17303     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
17304   }
17305 
17306   unsigned Offset = UndefLower ? HalfNumElts : 0;
17307   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
17308                      DAG.getIntPtrConstant(Offset, DL));
17309 }
17310 
17311 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
17312 /// This allows for fast cases such as subvector extraction/insertion
17313 /// or shuffling smaller vector types which can lower more efficiently.
17314 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
17315                                          SDValue V2, ArrayRef<int> Mask,
17316                                          const X86Subtarget &Subtarget,
17317                                          SelectionDAG &DAG) {
17318   assert((VT.is256BitVector() || VT.is512BitVector()) &&
17319          "Expected 256-bit or 512-bit vector");
17320 
17321   bool UndefLower = isUndefLowerHalf(Mask);
17322   if (!UndefLower && !isUndefUpperHalf(Mask))
17323     return SDValue();
17324 
17325   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
17326          "Completely undef shuffle mask should have been simplified already");
17327 
17328   // Upper half is undef and lower half is whole upper subvector.
17329   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17330   MVT HalfVT = VT.getHalfNumVectorElementsVT();
17331   unsigned HalfNumElts = HalfVT.getVectorNumElements();
17332   if (!UndefLower &&
17333       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
17334     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
17335                              DAG.getIntPtrConstant(HalfNumElts, DL));
17336     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
17337                        DAG.getIntPtrConstant(0, DL));
17338   }
17339 
17340   // Lower half is undef and upper half is whole lower subvector.
17341   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17342   if (UndefLower &&
17343       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
17344     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
17345                              DAG.getIntPtrConstant(0, DL));
17346     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
17347                        DAG.getIntPtrConstant(HalfNumElts, DL));
17348   }
17349 
17350   int HalfIdx1, HalfIdx2;
17351   SmallVector<int, 8> HalfMask(HalfNumElts);
17352   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
17353     return SDValue();
17354 
17355   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
17356 
17357   // Only shuffle the halves of the inputs when useful.
17358   unsigned NumLowerHalves =
17359       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
17360   unsigned NumUpperHalves =
17361       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
17362   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
17363 
17364   // Determine the larger pattern of undef/halves, then decide if it's worth
17365   // splitting the shuffle based on subtarget capabilities and types.
17366   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
17367   if (!UndefLower) {
17368     // XXXXuuuu: no insert is needed.
17369     // Always extract lowers when setting lower - these are all free subreg ops.
17370     if (NumUpperHalves == 0)
17371       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17372                                    UndefLower, DAG);
17373 
17374     if (NumUpperHalves == 1) {
17375       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
17376       if (Subtarget.hasAVX2()) {
17377         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
17378         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
17379             !is128BitUnpackShuffleMask(HalfMask, DAG) &&
17380             (!isSingleSHUFPSMask(HalfMask) ||
17381              Subtarget.hasFastVariableCrossLaneShuffle()))
17382           return SDValue();
17383         // If this is a unary shuffle (assume that the 2nd operand is
17384         // canonicalized to undef), then we can use vpermpd. Otherwise, we
17385         // are better off extracting the upper half of 1 operand and using a
17386         // narrow shuffle.
17387         if (EltWidth == 64 && V2.isUndef())
17388           return SDValue();
17389       }
17390       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
17391       if (Subtarget.hasAVX512() && VT.is512BitVector())
17392         return SDValue();
17393       // Extract + narrow shuffle is better than the wide alternative.
17394       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17395                                    UndefLower, DAG);
17396     }
17397 
17398     // Don't extract both uppers, instead shuffle and then extract.
17399     assert(NumUpperHalves == 2 && "Half vector count went wrong");
17400     return SDValue();
17401   }
17402 
17403   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
17404   if (NumUpperHalves == 0) {
17405     // AVX2 has efficient 64-bit element cross-lane shuffles.
17406     // TODO: Refine to account for unary shuffle, splat, and other masks?
17407     if (Subtarget.hasAVX2() && EltWidth == 64)
17408       return SDValue();
17409     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
17410     if (Subtarget.hasAVX512() && VT.is512BitVector())
17411       return SDValue();
17412     // Narrow shuffle + insert is better than the wide alternative.
17413     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17414                                  UndefLower, DAG);
17415   }
17416 
17417   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
17418   return SDValue();
17419 }
17420 
17421 /// Test whether the specified input (0 or 1) is in-place blended by the
17422 /// given mask.
17423 ///
17424 /// This returns true if the elements from a particular input are already in the
17425 /// slot required by the given mask and require no permutation.
17426 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
17427   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
17428   int Size = Mask.size();
17429   for (int i = 0; i < Size; ++i)
17430     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
17431       return false;
17432 
17433   return true;
17434 }
17435 
17436 /// Handle case where shuffle sources are coming from the same 128-bit lane and
17437 /// every lane can be represented as the same repeating mask - allowing us to
17438 /// shuffle the sources with the repeating shuffle and then permute the result
17439 /// to the destination lanes.
17440 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
17441     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
17442     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
17443   int NumElts = VT.getVectorNumElements();
17444   int NumLanes = VT.getSizeInBits() / 128;
17445   int NumLaneElts = NumElts / NumLanes;
17446 
17447   // On AVX2 we may be able to just shuffle the lowest elements and then
17448   // broadcast the result.
17449   if (Subtarget.hasAVX2()) {
17450     for (unsigned BroadcastSize : {16, 32, 64}) {
17451       if (BroadcastSize <= VT.getScalarSizeInBits())
17452         continue;
17453       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
17454 
17455       // Attempt to match a repeating pattern every NumBroadcastElts,
17456       // accounting for UNDEFs but only references the lowest 128-bit
17457       // lane of the inputs.
17458       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
17459         for (int i = 0; i != NumElts; i += NumBroadcastElts)
17460           for (int j = 0; j != NumBroadcastElts; ++j) {
17461             int M = Mask[i + j];
17462             if (M < 0)
17463               continue;
17464             int &R = RepeatMask[j];
17465             if (0 != ((M % NumElts) / NumLaneElts))
17466               return false;
17467             if (0 <= R && R != M)
17468               return false;
17469             R = M;
17470           }
17471         return true;
17472       };
17473 
17474       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
17475       if (!FindRepeatingBroadcastMask(RepeatMask))
17476         continue;
17477 
17478       // Shuffle the (lowest) repeated elements in place for broadcast.
17479       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
17480 
17481       // Shuffle the actual broadcast.
17482       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
17483       for (int i = 0; i != NumElts; i += NumBroadcastElts)
17484         for (int j = 0; j != NumBroadcastElts; ++j)
17485           BroadcastMask[i + j] = j;
17486       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
17487                                   BroadcastMask);
17488     }
17489   }
17490 
17491   // Bail if the shuffle mask doesn't cross 128-bit lanes.
17492   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
17493     return SDValue();
17494 
17495   // Bail if we already have a repeated lane shuffle mask.
17496   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
17497     return SDValue();
17498 
17499   // Helper to look for repeated mask in each split sublane, and that those
17500   // sublanes can then be permuted into place.
17501   auto ShuffleSubLanes = [&](int SubLaneScale) {
17502     int NumSubLanes = NumLanes * SubLaneScale;
17503     int NumSubLaneElts = NumLaneElts / SubLaneScale;
17504 
17505     // Check that all the sources are coming from the same lane and see if we
17506     // can form a repeating shuffle mask (local to each sub-lane). At the same
17507     // time, determine the source sub-lane for each destination sub-lane.
17508     int TopSrcSubLane = -1;
17509     SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
17510     SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
17511         SubLaneScale,
17512         SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
17513 
17514     for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
17515       // Extract the sub-lane mask, check that it all comes from the same lane
17516       // and normalize the mask entries to come from the first lane.
17517       int SrcLane = -1;
17518       SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
17519       for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
17520         int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
17521         if (M < 0)
17522           continue;
17523         int Lane = (M % NumElts) / NumLaneElts;
17524         if ((0 <= SrcLane) && (SrcLane != Lane))
17525           return SDValue();
17526         SrcLane = Lane;
17527         int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
17528         SubLaneMask[Elt] = LocalM;
17529       }
17530 
17531       // Whole sub-lane is UNDEF.
17532       if (SrcLane < 0)
17533         continue;
17534 
17535       // Attempt to match against the candidate repeated sub-lane masks.
17536       for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
17537         auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
17538           for (int i = 0; i != NumSubLaneElts; ++i) {
17539             if (M1[i] < 0 || M2[i] < 0)
17540               continue;
17541             if (M1[i] != M2[i])
17542               return false;
17543           }
17544           return true;
17545         };
17546 
17547         auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
17548         if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
17549           continue;
17550 
17551         // Merge the sub-lane mask into the matching repeated sub-lane mask.
17552         for (int i = 0; i != NumSubLaneElts; ++i) {
17553           int M = SubLaneMask[i];
17554           if (M < 0)
17555             continue;
17556           assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
17557                  "Unexpected mask element");
17558           RepeatedSubLaneMask[i] = M;
17559         }
17560 
17561         // Track the top most source sub-lane - by setting the remaining to
17562         // UNDEF we can greatly simplify shuffle matching.
17563         int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
17564         TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
17565         Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
17566         break;
17567       }
17568 
17569       // Bail if we failed to find a matching repeated sub-lane mask.
17570       if (Dst2SrcSubLanes[DstSubLane] < 0)
17571         return SDValue();
17572     }
17573     assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
17574            "Unexpected source lane");
17575 
17576     // Create a repeating shuffle mask for the entire vector.
17577     SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
17578     for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
17579       int Lane = SubLane / SubLaneScale;
17580       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
17581       for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
17582         int M = RepeatedSubLaneMask[Elt];
17583         if (M < 0)
17584           continue;
17585         int Idx = (SubLane * NumSubLaneElts) + Elt;
17586         RepeatedMask[Idx] = M + (Lane * NumLaneElts);
17587       }
17588     }
17589     SDValue RepeatedShuffle =
17590         DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
17591 
17592     // Shuffle each source sub-lane to its destination.
17593     SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
17594     for (int i = 0; i != NumElts; i += NumSubLaneElts) {
17595       int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
17596       if (SrcSubLane < 0)
17597         continue;
17598       for (int j = 0; j != NumSubLaneElts; ++j)
17599         SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
17600     }
17601 
17602     return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
17603                                 SubLaneMask);
17604   };
17605 
17606   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
17607   // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
17608   // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
17609   // Otherwise we can only permute whole 128-bit lanes.
17610   int MinSubLaneScale = 1, MaxSubLaneScale = 1;
17611   if (Subtarget.hasAVX2() && VT.is256BitVector()) {
17612     bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
17613     MinSubLaneScale = 2;
17614     MaxSubLaneScale =
17615         (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
17616   }
17617   if (Subtarget.hasBWI() && VT == MVT::v64i8)
17618     MinSubLaneScale = MaxSubLaneScale = 4;
17619 
17620   for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
17621     if (SDValue Shuffle = ShuffleSubLanes(Scale))
17622       return Shuffle;
17623 
17624   return SDValue();
17625 }
17626 
17627 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
17628                                    bool &ForceV1Zero, bool &ForceV2Zero,
17629                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
17630                                    const APInt &Zeroable) {
17631   int NumElts = VT.getVectorNumElements();
17632   assert(VT.getScalarSizeInBits() == 64 &&
17633          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
17634          "Unexpected data type for VSHUFPD");
17635   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
17636          "Illegal shuffle mask");
17637 
17638   bool ZeroLane[2] = { true, true };
17639   for (int i = 0; i < NumElts; ++i)
17640     ZeroLane[i & 1] &= Zeroable[i];
17641 
17642   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
17643   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
17644   ShuffleImm = 0;
17645   bool ShufpdMask = true;
17646   bool CommutableMask = true;
17647   for (int i = 0; i < NumElts; ++i) {
17648     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
17649       continue;
17650     if (Mask[i] < 0)
17651       return false;
17652     int Val = (i & 6) + NumElts * (i & 1);
17653     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
17654     if (Mask[i] < Val || Mask[i] > Val + 1)
17655       ShufpdMask = false;
17656     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
17657       CommutableMask = false;
17658     ShuffleImm |= (Mask[i] % 2) << i;
17659   }
17660 
17661   if (!ShufpdMask && !CommutableMask)
17662     return false;
17663 
17664   if (!ShufpdMask && CommutableMask)
17665     std::swap(V1, V2);
17666 
17667   ForceV1Zero = ZeroLane[0];
17668   ForceV2Zero = ZeroLane[1];
17669   return true;
17670 }
17671 
17672 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
17673                                       SDValue V2, ArrayRef<int> Mask,
17674                                       const APInt &Zeroable,
17675                                       const X86Subtarget &Subtarget,
17676                                       SelectionDAG &DAG) {
17677   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
17678          "Unexpected data type for VSHUFPD");
17679 
17680   unsigned Immediate = 0;
17681   bool ForceV1Zero = false, ForceV2Zero = false;
17682   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
17683                               Mask, Zeroable))
17684     return SDValue();
17685 
17686   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
17687   if (ForceV1Zero)
17688     V1 = getZeroVector(VT, Subtarget, DAG, DL);
17689   if (ForceV2Zero)
17690     V2 = getZeroVector(VT, Subtarget, DAG, DL);
17691 
17692   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
17693                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
17694 }
17695 
17696 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17697 // by zeroable elements in the remaining 24 elements. Turn this into two
17698 // vmovqb instructions shuffled together.
17699 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
17700                                              SDValue V1, SDValue V2,
17701                                              ArrayRef<int> Mask,
17702                                              const APInt &Zeroable,
17703                                              SelectionDAG &DAG) {
17704   assert(VT == MVT::v32i8 && "Unexpected type!");
17705 
17706   // The first 8 indices should be every 8th element.
17707   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
17708     return SDValue();
17709 
17710   // Remaining elements need to be zeroable.
17711   if (Zeroable.countLeadingOnes() < (Mask.size() - 8))
17712     return SDValue();
17713 
17714   V1 = DAG.getBitcast(MVT::v4i64, V1);
17715   V2 = DAG.getBitcast(MVT::v4i64, V2);
17716 
17717   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
17718   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
17719 
17720   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
17721   // the upper bits of the result using an unpckldq.
17722   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
17723                                         { 0, 1, 2, 3, 16, 17, 18, 19,
17724                                           4, 5, 6, 7, 20, 21, 22, 23 });
17725   // Insert the unpckldq into a zero vector to widen to v32i8.
17726   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
17727                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
17728                      DAG.getIntPtrConstant(0, DL));
17729 }
17730 
17731 
17732 /// Handle lowering of 4-lane 64-bit floating point shuffles.
17733 ///
17734 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
17735 /// isn't available.
17736 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17737                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17738                                  const X86Subtarget &Subtarget,
17739                                  SelectionDAG &DAG) {
17740   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
17741   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
17742   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
17743 
17744   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
17745                                      Subtarget, DAG))
17746     return V;
17747 
17748   if (V2.isUndef()) {
17749     // Check for being able to broadcast a single element.
17750     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
17751                                                     Mask, Subtarget, DAG))
17752       return Broadcast;
17753 
17754     // Use low duplicate instructions for masks that match their pattern.
17755     if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
17756       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
17757 
17758     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
17759       // Non-half-crossing single input shuffles can be lowered with an
17760       // interleaved permutation.
17761       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17762                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
17763       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
17764                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17765     }
17766 
17767     // With AVX2 we have direct support for this permutation.
17768     if (Subtarget.hasAVX2())
17769       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
17770                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
17771 
17772     // Try to create an in-lane repeating shuffle mask and then shuffle the
17773     // results into the target lanes.
17774     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17775             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
17776       return V;
17777 
17778     // Try to permute the lanes and then use a per-lane permute.
17779     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
17780                                                         Mask, DAG, Subtarget))
17781       return V;
17782 
17783     // Otherwise, fall back.
17784     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
17785                                                DAG, Subtarget);
17786   }
17787 
17788   // Use dedicated unpack instructions for masks that match their pattern.
17789   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
17790     return V;
17791 
17792   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
17793                                           Zeroable, Subtarget, DAG))
17794     return Blend;
17795 
17796   // Check if the blend happens to exactly fit that of SHUFPD.
17797   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
17798                                           Zeroable, Subtarget, DAG))
17799     return Op;
17800 
17801   bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
17802   bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
17803 
17804   // If we have lane crossing shuffles AND they don't all come from the lower
17805   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
17806   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
17807   // canonicalize to a blend of splat which isn't necessary for this combine.
17808   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
17809       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
17810       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
17811       (V2.getOpcode() != ISD::BUILD_VECTOR))
17812     return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
17813 
17814   // If we have one input in place, then we can permute the other input and
17815   // blend the result.
17816   if (V1IsInPlace || V2IsInPlace)
17817     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
17818                                                 Subtarget, DAG);
17819 
17820   // Try to create an in-lane repeating shuffle mask and then shuffle the
17821   // results into the target lanes.
17822   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17823           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
17824     return V;
17825 
17826   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17827   // shuffle. However, if we have AVX2 and either inputs are already in place,
17828   // we will be able to shuffle even across lanes the other input in a single
17829   // instruction so skip this pattern.
17830   if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
17831     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
17832             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
17833       return V;
17834 
17835   // If we have VLX support, we can use VEXPAND.
17836   if (Subtarget.hasVLX())
17837     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
17838                                          DAG, Subtarget))
17839       return V;
17840 
17841   // If we have AVX2 then we always want to lower with a blend because an v4 we
17842   // can fully permute the elements.
17843   if (Subtarget.hasAVX2())
17844     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
17845                                                 Subtarget, DAG);
17846 
17847   // Otherwise fall back on generic lowering.
17848   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
17849                                     Subtarget, DAG);
17850 }
17851 
17852 /// Handle lowering of 4-lane 64-bit integer shuffles.
17853 ///
17854 /// This routine is only called when we have AVX2 and thus a reasonable
17855 /// instruction set for v4i64 shuffling..
17856 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17857                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17858                                  const X86Subtarget &Subtarget,
17859                                  SelectionDAG &DAG) {
17860   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
17861   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
17862   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
17863   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
17864 
17865   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
17866                                      Subtarget, DAG))
17867     return V;
17868 
17869   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
17870                                           Zeroable, Subtarget, DAG))
17871     return Blend;
17872 
17873   // Check for being able to broadcast a single element.
17874   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
17875                                                   Subtarget, DAG))
17876     return Broadcast;
17877 
17878   if (V2.isUndef()) {
17879     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17880     // can use lower latency instructions that will operate on both lanes.
17881     SmallVector<int, 2> RepeatedMask;
17882     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
17883       SmallVector<int, 4> PSHUFDMask;
17884       narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
17885       return DAG.getBitcast(
17886           MVT::v4i64,
17887           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
17888                       DAG.getBitcast(MVT::v8i32, V1),
17889                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17890     }
17891 
17892     // AVX2 provides a direct instruction for permuting a single input across
17893     // lanes.
17894     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
17895                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
17896   }
17897 
17898   // Try to use shift instructions.
17899   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
17900                                           Zeroable, Subtarget, DAG))
17901     return Shift;
17902 
17903   // If we have VLX support, we can use VALIGN or VEXPAND.
17904   if (Subtarget.hasVLX()) {
17905     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
17906                                               Subtarget, DAG))
17907       return Rotate;
17908 
17909     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
17910                                          DAG, Subtarget))
17911       return V;
17912   }
17913 
17914   // Try to use PALIGNR.
17915   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
17916                                                 Subtarget, DAG))
17917     return Rotate;
17918 
17919   // Use dedicated unpack instructions for masks that match their pattern.
17920   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
17921     return V;
17922 
17923   bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
17924   bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
17925 
17926   // If we have one input in place, then we can permute the other input and
17927   // blend the result.
17928   if (V1IsInPlace || V2IsInPlace)
17929     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17930                                                 Subtarget, DAG);
17931 
17932   // Try to create an in-lane repeating shuffle mask and then shuffle the
17933   // results into the target lanes.
17934   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17935           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17936     return V;
17937 
17938   // Try to lower to PERMQ(BLENDD(V1,V2)).
17939   if (SDValue V =
17940           lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
17941     return V;
17942 
17943   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17944   // shuffle. However, if we have AVX2 and either inputs are already in place,
17945   // we will be able to shuffle even across lanes the other input in a single
17946   // instruction so skip this pattern.
17947   if (!V1IsInPlace && !V2IsInPlace)
17948     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17949             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17950       return Result;
17951 
17952   // Otherwise fall back on generic blend lowering.
17953   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17954                                               Subtarget, DAG);
17955 }
17956 
17957 /// Handle lowering of 8-lane 32-bit floating point shuffles.
17958 ///
17959 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
17960 /// isn't available.
17961 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17962                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17963                                  const X86Subtarget &Subtarget,
17964                                  SelectionDAG &DAG) {
17965   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17966   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17967   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17968 
17969   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
17970                                           Zeroable, Subtarget, DAG))
17971     return Blend;
17972 
17973   // Check for being able to broadcast a single element.
17974   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
17975                                                   Subtarget, DAG))
17976     return Broadcast;
17977 
17978   // If the shuffle mask is repeated in each 128-bit lane, we have many more
17979   // options to efficiently lower the shuffle.
17980   SmallVector<int, 4> RepeatedMask;
17981   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
17982     assert(RepeatedMask.size() == 4 &&
17983            "Repeated masks must be half the mask width!");
17984 
17985     // Use even/odd duplicate instructions for masks that match their pattern.
17986     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17987       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
17988     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17989       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
17990 
17991     if (V2.isUndef())
17992       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
17993                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17994 
17995     // Use dedicated unpack instructions for masks that match their pattern.
17996     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
17997       return V;
17998 
17999     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
18000     // have already handled any direct blends.
18001     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
18002   }
18003 
18004   // Try to create an in-lane repeating shuffle mask and then shuffle the
18005   // results into the target lanes.
18006   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18007           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
18008     return V;
18009 
18010   // If we have a single input shuffle with different shuffle patterns in the
18011   // two 128-bit lanes use the variable mask to VPERMILPS.
18012   if (V2.isUndef()) {
18013     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
18014       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
18015       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
18016     }
18017     if (Subtarget.hasAVX2()) {
18018       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
18019       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
18020     }
18021     // Otherwise, fall back.
18022     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
18023                                                DAG, Subtarget);
18024   }
18025 
18026   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18027   // shuffle.
18028   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18029           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
18030     return Result;
18031 
18032   // If we have VLX support, we can use VEXPAND.
18033   if (Subtarget.hasVLX())
18034     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
18035                                          DAG, Subtarget))
18036       return V;
18037 
18038   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
18039   // since after split we get a more efficient code using vpunpcklwd and
18040   // vpunpckhwd instrs than vblend.
18041   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
18042     return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Subtarget,
18043                                       DAG);
18044 
18045   // If we have AVX2 then we always want to lower with a blend because at v8 we
18046   // can fully permute the elements.
18047   if (Subtarget.hasAVX2())
18048     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
18049                                                 Subtarget, DAG);
18050 
18051   // Otherwise fall back on generic lowering.
18052   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
18053                                     Subtarget, DAG);
18054 }
18055 
18056 /// Handle lowering of 8-lane 32-bit integer shuffles.
18057 ///
18058 /// This routine is only called when we have AVX2 and thus a reasonable
18059 /// instruction set for v8i32 shuffling..
18060 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18061                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18062                                  const X86Subtarget &Subtarget,
18063                                  SelectionDAG &DAG) {
18064   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
18065   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
18066   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18067   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
18068 
18069   // Whenever we can lower this as a zext, that instruction is strictly faster
18070   // than any alternative. It also allows us to fold memory operands into the
18071   // shuffle in many cases.
18072   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
18073                                                    Zeroable, Subtarget, DAG))
18074     return ZExt;
18075 
18076   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
18077   // since after split we get a more efficient code than vblend by using
18078   // vpunpcklwd and vpunpckhwd instrs.
18079   if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
18080       !Subtarget.hasAVX512())
18081     return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Subtarget,
18082                                       DAG);
18083 
18084   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
18085                                           Zeroable, Subtarget, DAG))
18086     return Blend;
18087 
18088   // Check for being able to broadcast a single element.
18089   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
18090                                                   Subtarget, DAG))
18091     return Broadcast;
18092 
18093   // If the shuffle mask is repeated in each 128-bit lane we can use more
18094   // efficient instructions that mirror the shuffles across the two 128-bit
18095   // lanes.
18096   SmallVector<int, 4> RepeatedMask;
18097   bool Is128BitLaneRepeatedShuffle =
18098       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
18099   if (Is128BitLaneRepeatedShuffle) {
18100     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
18101     if (V2.isUndef())
18102       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
18103                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18104 
18105     // Use dedicated unpack instructions for masks that match their pattern.
18106     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
18107       return V;
18108   }
18109 
18110   // Try to use shift instructions.
18111   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
18112                                           Zeroable, Subtarget, DAG))
18113     return Shift;
18114 
18115   // If we have VLX support, we can use VALIGN or EXPAND.
18116   if (Subtarget.hasVLX()) {
18117     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
18118                                               Subtarget, DAG))
18119       return Rotate;
18120 
18121     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
18122                                          DAG, Subtarget))
18123       return V;
18124   }
18125 
18126   // Try to use byte rotation instructions.
18127   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
18128                                                 Subtarget, DAG))
18129     return Rotate;
18130 
18131   // Try to create an in-lane repeating shuffle mask and then shuffle the
18132   // results into the target lanes.
18133   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18134           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
18135     return V;
18136 
18137   if (V2.isUndef()) {
18138     // Try to produce a fixed cross-128-bit lane permute followed by unpack
18139     // because that should be faster than the variable permute alternatives.
18140     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
18141       return V;
18142 
18143     // If the shuffle patterns aren't repeated but it's a single input, directly
18144     // generate a cross-lane VPERMD instruction.
18145     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
18146     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
18147   }
18148 
18149   // Assume that a single SHUFPS is faster than an alternative sequence of
18150   // multiple instructions (even if the CPU has a domain penalty).
18151   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
18152   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
18153     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
18154     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
18155     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
18156                                             CastV1, CastV2, DAG);
18157     return DAG.getBitcast(MVT::v8i32, ShufPS);
18158   }
18159 
18160   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18161   // shuffle.
18162   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18163           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
18164     return Result;
18165 
18166   // Otherwise fall back on generic blend lowering.
18167   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
18168                                               Subtarget, DAG);
18169 }
18170 
18171 /// Handle lowering of 16-lane 16-bit integer shuffles.
18172 ///
18173 /// This routine is only called when we have AVX2 and thus a reasonable
18174 /// instruction set for v16i16 shuffling..
18175 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18176                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18177                                   const X86Subtarget &Subtarget,
18178                                   SelectionDAG &DAG) {
18179   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
18180   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
18181   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
18182   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
18183 
18184   // Whenever we can lower this as a zext, that instruction is strictly faster
18185   // than any alternative. It also allows us to fold memory operands into the
18186   // shuffle in many cases.
18187   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18188           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18189     return ZExt;
18190 
18191   // Check for being able to broadcast a single element.
18192   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
18193                                                   Subtarget, DAG))
18194     return Broadcast;
18195 
18196   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
18197                                           Zeroable, Subtarget, DAG))
18198     return Blend;
18199 
18200   // Use dedicated unpack instructions for masks that match their pattern.
18201   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
18202     return V;
18203 
18204   // Use dedicated pack instructions for masks that match their pattern.
18205   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
18206                                        Subtarget))
18207     return V;
18208 
18209   // Try to use lower using a truncation.
18210   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
18211                                        Subtarget, DAG))
18212     return V;
18213 
18214   // Try to use shift instructions.
18215   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
18216                                           Zeroable, Subtarget, DAG))
18217     return Shift;
18218 
18219   // Try to use byte rotation instructions.
18220   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
18221                                                 Subtarget, DAG))
18222     return Rotate;
18223 
18224   // Try to create an in-lane repeating shuffle mask and then shuffle the
18225   // results into the target lanes.
18226   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18227           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
18228     return V;
18229 
18230   if (V2.isUndef()) {
18231     // Try to use bit rotation instructions.
18232     if (SDValue Rotate =
18233             lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
18234       return Rotate;
18235 
18236     // Try to produce a fixed cross-128-bit lane permute followed by unpack
18237     // because that should be faster than the variable permute alternatives.
18238     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
18239       return V;
18240 
18241     // There are no generalized cross-lane shuffle operations available on i16
18242     // element types.
18243     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
18244       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
18245               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
18246         return V;
18247 
18248       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
18249                                                  DAG, Subtarget);
18250     }
18251 
18252     SmallVector<int, 8> RepeatedMask;
18253     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
18254       // As this is a single-input shuffle, the repeated mask should be
18255       // a strictly valid v8i16 mask that we can pass through to the v8i16
18256       // lowering to handle even the v16 case.
18257       return lowerV8I16GeneralSingleInputShuffle(
18258           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
18259     }
18260   }
18261 
18262   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
18263                                               Zeroable, Subtarget, DAG))
18264     return PSHUFB;
18265 
18266   // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
18267   if (Subtarget.hasBWI())
18268     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
18269 
18270   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18271   // shuffle.
18272   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18273           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
18274     return Result;
18275 
18276   // Try to permute the lanes and then use a per-lane permute.
18277   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
18278           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
18279     return V;
18280 
18281   // Otherwise fall back on generic lowering.
18282   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
18283                                     Subtarget, DAG);
18284 }
18285 
18286 /// Handle lowering of 32-lane 8-bit integer shuffles.
18287 ///
18288 /// This routine is only called when we have AVX2 and thus a reasonable
18289 /// instruction set for v32i8 shuffling..
18290 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18291                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18292                                  const X86Subtarget &Subtarget,
18293                                  SelectionDAG &DAG) {
18294   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
18295   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
18296   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
18297   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
18298 
18299   // Whenever we can lower this as a zext, that instruction is strictly faster
18300   // than any alternative. It also allows us to fold memory operands into the
18301   // shuffle in many cases.
18302   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
18303                                                    Zeroable, Subtarget, DAG))
18304     return ZExt;
18305 
18306   // Check for being able to broadcast a single element.
18307   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
18308                                                   Subtarget, DAG))
18309     return Broadcast;
18310 
18311   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
18312                                           Zeroable, Subtarget, DAG))
18313     return Blend;
18314 
18315   // Use dedicated unpack instructions for masks that match their pattern.
18316   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
18317     return V;
18318 
18319   // Use dedicated pack instructions for masks that match their pattern.
18320   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
18321                                        Subtarget))
18322     return V;
18323 
18324   // Try to use lower using a truncation.
18325   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
18326                                        Subtarget, DAG))
18327     return V;
18328 
18329   // Try to use shift instructions.
18330   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
18331                                           Zeroable, Subtarget, DAG))
18332     return Shift;
18333 
18334   // Try to use byte rotation instructions.
18335   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
18336                                                 Subtarget, DAG))
18337     return Rotate;
18338 
18339   // Try to use bit rotation instructions.
18340   if (V2.isUndef())
18341     if (SDValue Rotate =
18342             lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
18343       return Rotate;
18344 
18345   // Try to create an in-lane repeating shuffle mask and then shuffle the
18346   // results into the target lanes.
18347   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18348           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
18349     return V;
18350 
18351   // There are no generalized cross-lane shuffle operations available on i8
18352   // element types.
18353   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
18354     // Try to produce a fixed cross-128-bit lane permute followed by unpack
18355     // because that should be faster than the variable permute alternatives.
18356     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
18357       return V;
18358 
18359     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
18360             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
18361       return V;
18362 
18363     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
18364                                                DAG, Subtarget);
18365   }
18366 
18367   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
18368                                               Zeroable, Subtarget, DAG))
18369     return PSHUFB;
18370 
18371   // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
18372   if (Subtarget.hasVBMI())
18373     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
18374 
18375   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18376   // shuffle.
18377   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18378           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
18379     return Result;
18380 
18381   // Try to permute the lanes and then use a per-lane permute.
18382   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
18383           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
18384     return V;
18385 
18386   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
18387   // by zeroable elements in the remaining 24 elements. Turn this into two
18388   // vmovqb instructions shuffled together.
18389   if (Subtarget.hasVLX())
18390     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
18391                                                   Mask, Zeroable, DAG))
18392       return V;
18393 
18394   // Otherwise fall back on generic lowering.
18395   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
18396                                     Subtarget, DAG);
18397 }
18398 
18399 /// High-level routine to lower various 256-bit x86 vector shuffles.
18400 ///
18401 /// This routine either breaks down the specific type of a 256-bit x86 vector
18402 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
18403 /// together based on the available instructions.
18404 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
18405                                   SDValue V1, SDValue V2, const APInt &Zeroable,
18406                                   const X86Subtarget &Subtarget,
18407                                   SelectionDAG &DAG) {
18408   // If we have a single input to the zero element, insert that into V1 if we
18409   // can do so cheaply.
18410   int NumElts = VT.getVectorNumElements();
18411   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18412 
18413   if (NumV2Elements == 1 && Mask[0] >= NumElts)
18414     if (SDValue Insertion = lowerShuffleAsElementInsertion(
18415             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18416       return Insertion;
18417 
18418   // Handle special cases where the lower or upper half is UNDEF.
18419   if (SDValue V =
18420           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18421     return V;
18422 
18423   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
18424   // can check for those subtargets here and avoid much of the subtarget
18425   // querying in the per-vector-type lowering routines. With AVX1 we have
18426   // essentially *zero* ability to manipulate a 256-bit vector with integer
18427   // types. Since we'll use floating point types there eventually, just
18428   // immediately cast everything to a float and operate entirely in that domain.
18429   if (VT.isInteger() && !Subtarget.hasAVX2()) {
18430     int ElementBits = VT.getScalarSizeInBits();
18431     if (ElementBits < 32) {
18432       // No floating point type available, if we can't use the bit operations
18433       // for masking/blending then decompose into 128-bit vectors.
18434       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
18435                                             Subtarget, DAG))
18436         return V;
18437       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18438         return V;
18439       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
18440     }
18441 
18442     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
18443                                 VT.getVectorNumElements());
18444     V1 = DAG.getBitcast(FpVT, V1);
18445     V2 = DAG.getBitcast(FpVT, V2);
18446     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
18447   }
18448 
18449   if (VT == MVT::v16f16) {
18450     V1 = DAG.getBitcast(MVT::v16i16, V1);
18451     V2 = DAG.getBitcast(MVT::v16i16, V2);
18452     return DAG.getBitcast(MVT::v16f16,
18453                           DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
18454   }
18455 
18456   switch (VT.SimpleTy) {
18457   case MVT::v4f64:
18458     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18459   case MVT::v4i64:
18460     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18461   case MVT::v8f32:
18462     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18463   case MVT::v8i32:
18464     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18465   case MVT::v16i16:
18466     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18467   case MVT::v32i8:
18468     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18469 
18470   default:
18471     llvm_unreachable("Not a valid 256-bit x86 vector type!");
18472   }
18473 }
18474 
18475 /// Try to lower a vector shuffle as a 128-bit shuffles.
18476 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
18477                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18478                                   const X86Subtarget &Subtarget,
18479                                   SelectionDAG &DAG) {
18480   assert(VT.getScalarSizeInBits() == 64 &&
18481          "Unexpected element type size for 128bit shuffle.");
18482 
18483   // To handle 256 bit vector requires VLX and most probably
18484   // function lowerV2X128VectorShuffle() is better solution.
18485   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
18486 
18487   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
18488   SmallVector<int, 4> Widened128Mask;
18489   if (!canWidenShuffleElements(Mask, Widened128Mask))
18490     return SDValue();
18491   assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
18492 
18493   // Try to use an insert into a zero vector.
18494   if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
18495       (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
18496     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
18497     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
18498     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
18499                               DAG.getIntPtrConstant(0, DL));
18500     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18501                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
18502                        DAG.getIntPtrConstant(0, DL));
18503   }
18504 
18505   // Check for patterns which can be matched with a single insert of a 256-bit
18506   // subvector.
18507   bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
18508   if (OnlyUsesV1 ||
18509       isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
18510     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
18511     SDValue SubVec =
18512         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
18513                     DAG.getIntPtrConstant(0, DL));
18514     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
18515                        DAG.getIntPtrConstant(4, DL));
18516   }
18517 
18518   // See if this is an insertion of the lower 128-bits of V2 into V1.
18519   bool IsInsert = true;
18520   int V2Index = -1;
18521   for (int i = 0; i < 4; ++i) {
18522     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
18523     if (Widened128Mask[i] < 0)
18524       continue;
18525 
18526     // Make sure all V1 subvectors are in place.
18527     if (Widened128Mask[i] < 4) {
18528       if (Widened128Mask[i] != i) {
18529         IsInsert = false;
18530         break;
18531       }
18532     } else {
18533       // Make sure we only have a single V2 index and its the lowest 128-bits.
18534       if (V2Index >= 0 || Widened128Mask[i] != 4) {
18535         IsInsert = false;
18536         break;
18537       }
18538       V2Index = i;
18539     }
18540   }
18541   if (IsInsert && V2Index >= 0) {
18542     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
18543     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
18544                                  DAG.getIntPtrConstant(0, DL));
18545     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
18546   }
18547 
18548   // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
18549   // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
18550   // possible we at least ensure the lanes stay sequential to help later
18551   // combines.
18552   SmallVector<int, 2> Widened256Mask;
18553   if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
18554     Widened128Mask.clear();
18555     narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
18556   }
18557 
18558   // Try to lower to vshuf64x2/vshuf32x4.
18559   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
18560   unsigned PermMask = 0;
18561   // Insure elements came from the same Op.
18562   for (int i = 0; i < 4; ++i) {
18563     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
18564     if (Widened128Mask[i] < 0)
18565       continue;
18566 
18567     SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
18568     unsigned OpIndex = i / 2;
18569     if (Ops[OpIndex].isUndef())
18570       Ops[OpIndex] = Op;
18571     else if (Ops[OpIndex] != Op)
18572       return SDValue();
18573 
18574     // Convert the 128-bit shuffle mask selection values into 128-bit selection
18575     // bits defined by a vshuf64x2 instruction's immediate control byte.
18576     PermMask |= (Widened128Mask[i] % 4) << (i * 2);
18577   }
18578 
18579   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
18580                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
18581 }
18582 
18583 /// Handle lowering of 8-lane 64-bit floating point shuffles.
18584 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18585                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18586                                  const X86Subtarget &Subtarget,
18587                                  SelectionDAG &DAG) {
18588   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
18589   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
18590   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18591 
18592   if (V2.isUndef()) {
18593     // Use low duplicate instructions for masks that match their pattern.
18594     if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
18595       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
18596 
18597     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
18598       // Non-half-crossing single input shuffles can be lowered with an
18599       // interleaved permutation.
18600       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
18601                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
18602                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
18603                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
18604       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
18605                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
18606     }
18607 
18608     SmallVector<int, 4> RepeatedMask;
18609     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
18610       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
18611                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18612   }
18613 
18614   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
18615                                            V2, Subtarget, DAG))
18616     return Shuf128;
18617 
18618   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
18619     return Unpck;
18620 
18621   // Check if the blend happens to exactly fit that of SHUFPD.
18622   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
18623                                           Zeroable, Subtarget, DAG))
18624     return Op;
18625 
18626   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
18627                                        DAG, Subtarget))
18628     return V;
18629 
18630   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
18631                                           Zeroable, Subtarget, DAG))
18632     return Blend;
18633 
18634   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
18635 }
18636 
18637 /// Handle lowering of 16-lane 32-bit floating point shuffles.
18638 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18639                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18640                                   const X86Subtarget &Subtarget,
18641                                   SelectionDAG &DAG) {
18642   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
18643   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
18644   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
18645 
18646   // If the shuffle mask is repeated in each 128-bit lane, we have many more
18647   // options to efficiently lower the shuffle.
18648   SmallVector<int, 4> RepeatedMask;
18649   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
18650     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
18651 
18652     // Use even/odd duplicate instructions for masks that match their pattern.
18653     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
18654       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
18655     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
18656       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
18657 
18658     if (V2.isUndef())
18659       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
18660                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18661 
18662     // Use dedicated unpack instructions for masks that match their pattern.
18663     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
18664       return V;
18665 
18666     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
18667                                             Zeroable, Subtarget, DAG))
18668       return Blend;
18669 
18670     // Otherwise, fall back to a SHUFPS sequence.
18671     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
18672   }
18673 
18674   // Try to create an in-lane repeating shuffle mask and then shuffle the
18675   // results into the target lanes.
18676   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18677           DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
18678     return V;
18679 
18680   // If we have a single input shuffle with different shuffle patterns in the
18681   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
18682   if (V2.isUndef() &&
18683       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
18684     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
18685     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
18686   }
18687 
18688   // If we have AVX512F support, we can use VEXPAND.
18689   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
18690                                              V1, V2, DAG, Subtarget))
18691     return V;
18692 
18693   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
18694 }
18695 
18696 /// Handle lowering of 8-lane 64-bit integer shuffles.
18697 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18698                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18699                                  const X86Subtarget &Subtarget,
18700                                  SelectionDAG &DAG) {
18701   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
18702   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
18703   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18704 
18705   if (V2.isUndef()) {
18706     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
18707     // can use lower latency instructions that will operate on all four
18708     // 128-bit lanes.
18709     SmallVector<int, 2> Repeated128Mask;
18710     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
18711       SmallVector<int, 4> PSHUFDMask;
18712       narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
18713       return DAG.getBitcast(
18714           MVT::v8i64,
18715           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
18716                       DAG.getBitcast(MVT::v16i32, V1),
18717                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
18718     }
18719 
18720     SmallVector<int, 4> Repeated256Mask;
18721     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
18722       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
18723                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
18724   }
18725 
18726   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
18727                                            V2, Subtarget, DAG))
18728     return Shuf128;
18729 
18730   // Try to use shift instructions.
18731   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
18732                                           Zeroable, Subtarget, DAG))
18733     return Shift;
18734 
18735   // Try to use VALIGN.
18736   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
18737                                             Subtarget, DAG))
18738     return Rotate;
18739 
18740   // Try to use PALIGNR.
18741   if (Subtarget.hasBWI())
18742     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
18743                                                   Subtarget, DAG))
18744       return Rotate;
18745 
18746   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
18747     return Unpck;
18748 
18749   // If we have AVX512F support, we can use VEXPAND.
18750   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
18751                                        DAG, Subtarget))
18752     return V;
18753 
18754   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
18755                                           Zeroable, Subtarget, DAG))
18756     return Blend;
18757 
18758   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
18759 }
18760 
18761 /// Handle lowering of 16-lane 32-bit integer shuffles.
18762 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18763                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18764                                   const X86Subtarget &Subtarget,
18765                                   SelectionDAG &DAG) {
18766   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
18767   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
18768   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
18769 
18770   // Whenever we can lower this as a zext, that instruction is strictly faster
18771   // than any alternative. It also allows us to fold memory operands into the
18772   // shuffle in many cases.
18773   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18774           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
18775     return ZExt;
18776 
18777   // If the shuffle mask is repeated in each 128-bit lane we can use more
18778   // efficient instructions that mirror the shuffles across the four 128-bit
18779   // lanes.
18780   SmallVector<int, 4> RepeatedMask;
18781   bool Is128BitLaneRepeatedShuffle =
18782       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
18783   if (Is128BitLaneRepeatedShuffle) {
18784     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
18785     if (V2.isUndef())
18786       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
18787                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18788 
18789     // Use dedicated unpack instructions for masks that match their pattern.
18790     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
18791       return V;
18792   }
18793 
18794   // Try to use shift instructions.
18795   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
18796                                           Zeroable, Subtarget, DAG))
18797     return Shift;
18798 
18799   // Try to use VALIGN.
18800   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
18801                                             Subtarget, DAG))
18802     return Rotate;
18803 
18804   // Try to use byte rotation instructions.
18805   if (Subtarget.hasBWI())
18806     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
18807                                                   Subtarget, DAG))
18808       return Rotate;
18809 
18810   // Assume that a single SHUFPS is faster than using a permv shuffle.
18811   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
18812   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
18813     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
18814     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
18815     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
18816                                             CastV1, CastV2, DAG);
18817     return DAG.getBitcast(MVT::v16i32, ShufPS);
18818   }
18819 
18820   // Try to create an in-lane repeating shuffle mask and then shuffle the
18821   // results into the target lanes.
18822   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18823           DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
18824     return V;
18825 
18826   // If we have AVX512F support, we can use VEXPAND.
18827   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
18828                                        DAG, Subtarget))
18829     return V;
18830 
18831   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
18832                                           Zeroable, Subtarget, DAG))
18833     return Blend;
18834 
18835   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
18836 }
18837 
18838 /// Handle lowering of 32-lane 16-bit integer shuffles.
18839 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18840                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18841                                   const X86Subtarget &Subtarget,
18842                                   SelectionDAG &DAG) {
18843   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18844   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18845   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
18846   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
18847 
18848   // Whenever we can lower this as a zext, that instruction is strictly faster
18849   // than any alternative. It also allows us to fold memory operands into the
18850   // shuffle in many cases.
18851   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18852           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18853     return ZExt;
18854 
18855   // Use dedicated unpack instructions for masks that match their pattern.
18856   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
18857     return V;
18858 
18859   // Use dedicated pack instructions for masks that match their pattern.
18860   if (SDValue V =
18861           lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
18862     return V;
18863 
18864   // Try to use shift instructions.
18865   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
18866                                           Zeroable, Subtarget, DAG))
18867     return Shift;
18868 
18869   // Try to use byte rotation instructions.
18870   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
18871                                                 Subtarget, DAG))
18872     return Rotate;
18873 
18874   if (V2.isUndef()) {
18875     // Try to use bit rotation instructions.
18876     if (SDValue Rotate =
18877             lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
18878       return Rotate;
18879 
18880     SmallVector<int, 8> RepeatedMask;
18881     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
18882       // As this is a single-input shuffle, the repeated mask should be
18883       // a strictly valid v8i16 mask that we can pass through to the v8i16
18884       // lowering to handle even the v32 case.
18885       return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
18886                                                  RepeatedMask, Subtarget, DAG);
18887     }
18888   }
18889 
18890   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
18891                                           Zeroable, Subtarget, DAG))
18892     return Blend;
18893 
18894   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
18895                                               Zeroable, Subtarget, DAG))
18896     return PSHUFB;
18897 
18898   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
18899 }
18900 
18901 /// Handle lowering of 64-lane 8-bit integer shuffles.
18902 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18903                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18904                                  const X86Subtarget &Subtarget,
18905                                  SelectionDAG &DAG) {
18906   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18907   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18908   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
18909   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
18910 
18911   // Whenever we can lower this as a zext, that instruction is strictly faster
18912   // than any alternative. It also allows us to fold memory operands into the
18913   // shuffle in many cases.
18914   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18915           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
18916     return ZExt;
18917 
18918   // Use dedicated unpack instructions for masks that match their pattern.
18919   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
18920     return V;
18921 
18922   // Use dedicated pack instructions for masks that match their pattern.
18923   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
18924                                        Subtarget))
18925     return V;
18926 
18927   // Try to use shift instructions.
18928   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
18929                                           Zeroable, Subtarget, DAG))
18930     return Shift;
18931 
18932   // Try to use byte rotation instructions.
18933   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
18934                                                 Subtarget, DAG))
18935     return Rotate;
18936 
18937   // Try to use bit rotation instructions.
18938   if (V2.isUndef())
18939     if (SDValue Rotate =
18940             lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
18941       return Rotate;
18942 
18943   // Lower as AND if possible.
18944   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
18945                                              Zeroable, Subtarget, DAG))
18946     return Masked;
18947 
18948   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
18949                                               Zeroable, Subtarget, DAG))
18950     return PSHUFB;
18951 
18952   // Try to create an in-lane repeating shuffle mask and then shuffle the
18953   // results into the target lanes.
18954   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18955           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18956     return V;
18957 
18958   if (SDValue Result = lowerShuffleAsLanePermuteAndPermute(
18959           DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
18960     return Result;
18961 
18962   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
18963                                           Zeroable, Subtarget, DAG))
18964     return Blend;
18965 
18966   if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
18967     // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
18968     // PALIGNR will be cheaper than the second PSHUFB+OR.
18969     if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
18970                                                        Mask, Subtarget, DAG))
18971       return V;
18972 
18973     // If we can't directly blend but can use PSHUFB, that will be better as it
18974     // can both shuffle and set up the inefficient blend.
18975     bool V1InUse, V2InUse;
18976     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
18977                                         DAG, V1InUse, V2InUse);
18978   }
18979 
18980   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18981   // shuffle.
18982   if (!V2.isUndef())
18983     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18984             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18985       return Result;
18986 
18987   // VBMI can use VPERMV/VPERMV3 byte shuffles.
18988   if (Subtarget.hasVBMI())
18989     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
18990 
18991   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
18992 }
18993 
18994 /// High-level routine to lower various 512-bit x86 vector shuffles.
18995 ///
18996 /// This routine either breaks down the specific type of a 512-bit x86 vector
18997 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
18998 /// together based on the available instructions.
18999 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
19000                                   MVT VT, SDValue V1, SDValue V2,
19001                                   const APInt &Zeroable,
19002                                   const X86Subtarget &Subtarget,
19003                                   SelectionDAG &DAG) {
19004   assert(Subtarget.hasAVX512() &&
19005          "Cannot lower 512-bit vectors w/ basic ISA!");
19006 
19007   // If we have a single input to the zero element, insert that into V1 if we
19008   // can do so cheaply.
19009   int NumElts = Mask.size();
19010   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
19011 
19012   if (NumV2Elements == 1 && Mask[0] >= NumElts)
19013     if (SDValue Insertion = lowerShuffleAsElementInsertion(
19014             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
19015       return Insertion;
19016 
19017   // Handle special cases where the lower or upper half is UNDEF.
19018   if (SDValue V =
19019           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
19020     return V;
19021 
19022   // Check for being able to broadcast a single element.
19023   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
19024                                                   Subtarget, DAG))
19025     return Broadcast;
19026 
19027   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
19028     // Try using bit ops for masking and blending before falling back to
19029     // splitting.
19030     if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
19031                                           Subtarget, DAG))
19032       return V;
19033     if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
19034       return V;
19035 
19036     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
19037   }
19038 
19039   if (VT == MVT::v32f16) {
19040     V1 = DAG.getBitcast(MVT::v32i16, V1);
19041     V2 = DAG.getBitcast(MVT::v32i16, V2);
19042     return DAG.getBitcast(MVT::v32f16,
19043                           DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
19044   }
19045 
19046   // Dispatch to each element type for lowering. If we don't have support for
19047   // specific element type shuffles at 512 bits, immediately split them and
19048   // lower them. Each lowering routine of a given type is allowed to assume that
19049   // the requisite ISA extensions for that element type are available.
19050   switch (VT.SimpleTy) {
19051   case MVT::v8f64:
19052     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19053   case MVT::v16f32:
19054     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19055   case MVT::v8i64:
19056     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19057   case MVT::v16i32:
19058     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19059   case MVT::v32i16:
19060     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19061   case MVT::v64i8:
19062     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19063 
19064   default:
19065     llvm_unreachable("Not a valid 512-bit x86 vector type!");
19066   }
19067 }
19068 
19069 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
19070                                          MVT VT, SDValue V1, SDValue V2,
19071                                          const X86Subtarget &Subtarget,
19072                                          SelectionDAG &DAG) {
19073   // Shuffle should be unary.
19074   if (!V2.isUndef())
19075     return SDValue();
19076 
19077   int ShiftAmt = -1;
19078   int NumElts = Mask.size();
19079   for (int i = 0; i != NumElts; ++i) {
19080     int M = Mask[i];
19081     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
19082            "Unexpected mask index.");
19083     if (M < 0)
19084       continue;
19085 
19086     // The first non-undef element determines our shift amount.
19087     if (ShiftAmt < 0) {
19088       ShiftAmt = M - i;
19089       // Need to be shifting right.
19090       if (ShiftAmt <= 0)
19091         return SDValue();
19092     }
19093     // All non-undef elements must shift by the same amount.
19094     if (ShiftAmt != M - i)
19095       return SDValue();
19096   }
19097   assert(ShiftAmt >= 0 && "All undef?");
19098 
19099   // Great we found a shift right.
19100   MVT WideVT = VT;
19101   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
19102     WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19103   SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
19104                             DAG.getUNDEF(WideVT), V1,
19105                             DAG.getIntPtrConstant(0, DL));
19106   Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
19107                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
19108   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19109                      DAG.getIntPtrConstant(0, DL));
19110 }
19111 
19112 // Determine if this shuffle can be implemented with a KSHIFT instruction.
19113 // Returns the shift amount if possible or -1 if not. This is a simplified
19114 // version of matchShuffleAsShift.
19115 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
19116                                     int MaskOffset, const APInt &Zeroable) {
19117   int Size = Mask.size();
19118 
19119   auto CheckZeros = [&](int Shift, bool Left) {
19120     for (int j = 0; j < Shift; ++j)
19121       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
19122         return false;
19123 
19124     return true;
19125   };
19126 
19127   auto MatchShift = [&](int Shift, bool Left) {
19128     unsigned Pos = Left ? Shift : 0;
19129     unsigned Low = Left ? 0 : Shift;
19130     unsigned Len = Size - Shift;
19131     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
19132   };
19133 
19134   for (int Shift = 1; Shift != Size; ++Shift)
19135     for (bool Left : {true, false})
19136       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
19137         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
19138         return Shift;
19139       }
19140 
19141   return -1;
19142 }
19143 
19144 
19145 // Lower vXi1 vector shuffles.
19146 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
19147 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
19148 // vector, shuffle and then truncate it back.
19149 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
19150                                 MVT VT, SDValue V1, SDValue V2,
19151                                 const APInt &Zeroable,
19152                                 const X86Subtarget &Subtarget,
19153                                 SelectionDAG &DAG) {
19154   assert(Subtarget.hasAVX512() &&
19155          "Cannot lower 512-bit vectors w/o basic ISA!");
19156 
19157   int NumElts = Mask.size();
19158 
19159   // Try to recognize shuffles that are just padding a subvector with zeros.
19160   int SubvecElts = 0;
19161   int Src = -1;
19162   for (int i = 0; i != NumElts; ++i) {
19163     if (Mask[i] >= 0) {
19164       // Grab the source from the first valid mask. All subsequent elements need
19165       // to use this same source.
19166       if (Src < 0)
19167         Src = Mask[i] / NumElts;
19168       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
19169         break;
19170     }
19171 
19172     ++SubvecElts;
19173   }
19174   assert(SubvecElts != NumElts && "Identity shuffle?");
19175 
19176   // Clip to a power 2.
19177   SubvecElts = PowerOf2Floor(SubvecElts);
19178 
19179   // Make sure the number of zeroable bits in the top at least covers the bits
19180   // not covered by the subvector.
19181   if ((int)Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
19182     assert(Src >= 0 && "Expected a source!");
19183     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
19184     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
19185                                   Src == 0 ? V1 : V2,
19186                                   DAG.getIntPtrConstant(0, DL));
19187     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
19188                        DAG.getConstant(0, DL, VT),
19189                        Extract, DAG.getIntPtrConstant(0, DL));
19190   }
19191 
19192   // Try a simple shift right with undef elements. Later we'll try with zeros.
19193   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
19194                                                 DAG))
19195     return Shift;
19196 
19197   // Try to match KSHIFTs.
19198   unsigned Offset = 0;
19199   for (SDValue V : { V1, V2 }) {
19200     unsigned Opcode;
19201     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
19202     if (ShiftAmt >= 0) {
19203       MVT WideVT = VT;
19204       if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
19205         WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19206       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
19207                                 DAG.getUNDEF(WideVT), V,
19208                                 DAG.getIntPtrConstant(0, DL));
19209       // Widened right shifts need two shifts to ensure we shift in zeroes.
19210       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
19211         int WideElts = WideVT.getVectorNumElements();
19212         // Shift left to put the original vector in the MSBs of the new size.
19213         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
19214                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
19215         // Increase the shift amount to account for the left shift.
19216         ShiftAmt += WideElts - NumElts;
19217       }
19218 
19219       Res = DAG.getNode(Opcode, DL, WideVT, Res,
19220                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
19221       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19222                          DAG.getIntPtrConstant(0, DL));
19223     }
19224     Offset += NumElts; // Increment for next iteration.
19225   }
19226 
19227   // If we're broadcasting a SETCC result, try to broadcast the ops instead.
19228   // TODO: What other unary shuffles would benefit from this?
19229   if (isBroadcastShuffleMask(Mask) && V1.getOpcode() == ISD::SETCC &&
19230       V1->hasOneUse()) {
19231     SDValue Op0 = V1.getOperand(0);
19232     SDValue Op1 = V1.getOperand(1);
19233     ISD::CondCode CC = cast<CondCodeSDNode>(V1.getOperand(2))->get();
19234     EVT OpVT = Op0.getValueType();
19235     return DAG.getSetCC(
19236         DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
19237         DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
19238   }
19239 
19240   MVT ExtVT;
19241   switch (VT.SimpleTy) {
19242   default:
19243     llvm_unreachable("Expected a vector of i1 elements");
19244   case MVT::v2i1:
19245     ExtVT = MVT::v2i64;
19246     break;
19247   case MVT::v4i1:
19248     ExtVT = MVT::v4i32;
19249     break;
19250   case MVT::v8i1:
19251     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
19252     // shuffle.
19253     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
19254     break;
19255   case MVT::v16i1:
19256     // Take 512-bit type, unless we are avoiding 512-bit types and have the
19257     // 256-bit operation available.
19258     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
19259     break;
19260   case MVT::v32i1:
19261     // Take 512-bit type, unless we are avoiding 512-bit types and have the
19262     // 256-bit operation available.
19263     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
19264     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
19265     break;
19266   case MVT::v64i1:
19267     // Fall back to scalarization. FIXME: We can do better if the shuffle
19268     // can be partitioned cleanly.
19269     if (!Subtarget.useBWIRegs())
19270       return SDValue();
19271     ExtVT = MVT::v64i8;
19272     break;
19273   }
19274 
19275   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
19276   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
19277 
19278   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
19279   // i1 was sign extended we can use X86ISD::CVT2MASK.
19280   int NumElems = VT.getVectorNumElements();
19281   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
19282       (Subtarget.hasDQI() && (NumElems < 32)))
19283     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
19284                        Shuffle, ISD::SETGT);
19285 
19286   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
19287 }
19288 
19289 /// Helper function that returns true if the shuffle mask should be
19290 /// commuted to improve canonicalization.
19291 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
19292   int NumElements = Mask.size();
19293 
19294   int NumV1Elements = 0, NumV2Elements = 0;
19295   for (int M : Mask)
19296     if (M < 0)
19297       continue;
19298     else if (M < NumElements)
19299       ++NumV1Elements;
19300     else
19301       ++NumV2Elements;
19302 
19303   // Commute the shuffle as needed such that more elements come from V1 than
19304   // V2. This allows us to match the shuffle pattern strictly on how many
19305   // elements come from V1 without handling the symmetric cases.
19306   if (NumV2Elements > NumV1Elements)
19307     return true;
19308 
19309   assert(NumV1Elements > 0 && "No V1 indices");
19310 
19311   if (NumV2Elements == 0)
19312     return false;
19313 
19314   // When the number of V1 and V2 elements are the same, try to minimize the
19315   // number of uses of V2 in the low half of the vector. When that is tied,
19316   // ensure that the sum of indices for V1 is equal to or lower than the sum
19317   // indices for V2. When those are equal, try to ensure that the number of odd
19318   // indices for V1 is lower than the number of odd indices for V2.
19319   if (NumV1Elements == NumV2Elements) {
19320     int LowV1Elements = 0, LowV2Elements = 0;
19321     for (int M : Mask.slice(0, NumElements / 2))
19322       if (M >= NumElements)
19323         ++LowV2Elements;
19324       else if (M >= 0)
19325         ++LowV1Elements;
19326     if (LowV2Elements > LowV1Elements)
19327       return true;
19328     if (LowV2Elements == LowV1Elements) {
19329       int SumV1Indices = 0, SumV2Indices = 0;
19330       for (int i = 0, Size = Mask.size(); i < Size; ++i)
19331         if (Mask[i] >= NumElements)
19332           SumV2Indices += i;
19333         else if (Mask[i] >= 0)
19334           SumV1Indices += i;
19335       if (SumV2Indices < SumV1Indices)
19336         return true;
19337       if (SumV2Indices == SumV1Indices) {
19338         int NumV1OddIndices = 0, NumV2OddIndices = 0;
19339         for (int i = 0, Size = Mask.size(); i < Size; ++i)
19340           if (Mask[i] >= NumElements)
19341             NumV2OddIndices += i % 2;
19342           else if (Mask[i] >= 0)
19343             NumV1OddIndices += i % 2;
19344         if (NumV2OddIndices < NumV1OddIndices)
19345           return true;
19346       }
19347     }
19348   }
19349 
19350   return false;
19351 }
19352 
19353 // Forward declaration.
19354 static SDValue canonicalizeShuffleMaskWithHorizOp(
19355     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
19356     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
19357     const X86Subtarget &Subtarget);
19358 
19359     /// Top-level lowering for x86 vector shuffles.
19360 ///
19361 /// This handles decomposition, canonicalization, and lowering of all x86
19362 /// vector shuffles. Most of the specific lowering strategies are encapsulated
19363 /// above in helper routines. The canonicalization attempts to widen shuffles
19364 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
19365 /// s.t. only one of the two inputs needs to be tested, etc.
19366 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
19367                                    SelectionDAG &DAG) {
19368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
19369   ArrayRef<int> OrigMask = SVOp->getMask();
19370   SDValue V1 = Op.getOperand(0);
19371   SDValue V2 = Op.getOperand(1);
19372   MVT VT = Op.getSimpleValueType();
19373   int NumElements = VT.getVectorNumElements();
19374   SDLoc DL(Op);
19375   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
19376 
19377   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
19378          "Can't lower MMX shuffles");
19379 
19380   bool V1IsUndef = V1.isUndef();
19381   bool V2IsUndef = V2.isUndef();
19382   if (V1IsUndef && V2IsUndef)
19383     return DAG.getUNDEF(VT);
19384 
19385   // When we create a shuffle node we put the UNDEF node to second operand,
19386   // but in some cases the first operand may be transformed to UNDEF.
19387   // In this case we should just commute the node.
19388   if (V1IsUndef)
19389     return DAG.getCommutedVectorShuffle(*SVOp);
19390 
19391   // Check for non-undef masks pointing at an undef vector and make the masks
19392   // undef as well. This makes it easier to match the shuffle based solely on
19393   // the mask.
19394   if (V2IsUndef &&
19395       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
19396     SmallVector<int, 8> NewMask(OrigMask.begin(), OrigMask.end());
19397     for (int &M : NewMask)
19398       if (M >= NumElements)
19399         M = -1;
19400     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
19401   }
19402 
19403   // Check for illegal shuffle mask element index values.
19404   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
19405   (void)MaskUpperLimit;
19406   assert(llvm::all_of(OrigMask,
19407                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
19408          "Out of bounds shuffle index");
19409 
19410   // We actually see shuffles that are entirely re-arrangements of a set of
19411   // zero inputs. This mostly happens while decomposing complex shuffles into
19412   // simple ones. Directly lower these as a buildvector of zeros.
19413   APInt KnownUndef, KnownZero;
19414   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
19415 
19416   APInt Zeroable = KnownUndef | KnownZero;
19417   if (Zeroable.isAllOnes())
19418     return getZeroVector(VT, Subtarget, DAG, DL);
19419 
19420   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
19421 
19422   // Try to collapse shuffles into using a vector type with fewer elements but
19423   // wider element types. We cap this to not form integers or floating point
19424   // elements wider than 64 bits. It does not seem beneficial to form i128
19425   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
19426   SmallVector<int, 16> WidenedMask;
19427   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
19428       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
19429     // Shuffle mask widening should not interfere with a broadcast opportunity
19430     // by obfuscating the operands with bitcasts.
19431     // TODO: Avoid lowering directly from this top-level function: make this
19432     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
19433     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
19434                                                     Subtarget, DAG))
19435       return Broadcast;
19436 
19437     MVT NewEltVT = VT.isFloatingPoint()
19438                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
19439                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
19440     int NewNumElts = NumElements / 2;
19441     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
19442     // Make sure that the new vector type is legal. For example, v2f64 isn't
19443     // legal on SSE1.
19444     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
19445       if (V2IsZero) {
19446         // Modify the new Mask to take all zeros from the all-zero vector.
19447         // Choose indices that are blend-friendly.
19448         bool UsedZeroVector = false;
19449         assert(is_contained(WidenedMask, SM_SentinelZero) &&
19450                "V2's non-undef elements are used?!");
19451         for (int i = 0; i != NewNumElts; ++i)
19452           if (WidenedMask[i] == SM_SentinelZero) {
19453             WidenedMask[i] = i + NewNumElts;
19454             UsedZeroVector = true;
19455           }
19456         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
19457         // some elements to be undef.
19458         if (UsedZeroVector)
19459           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
19460       }
19461       V1 = DAG.getBitcast(NewVT, V1);
19462       V2 = DAG.getBitcast(NewVT, V2);
19463       return DAG.getBitcast(
19464           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
19465     }
19466   }
19467 
19468   SmallVector<SDValue> Ops = {V1, V2};
19469   SmallVector<int> Mask(OrigMask.begin(), OrigMask.end());
19470 
19471   // Canonicalize the shuffle with any horizontal ops inputs.
19472   // NOTE: This may update Ops and Mask.
19473   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
19474           Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
19475     return DAG.getBitcast(VT, HOp);
19476 
19477   V1 = DAG.getBitcast(VT, Ops[0]);
19478   V2 = DAG.getBitcast(VT, Ops[1]);
19479   assert(NumElements == (int)Mask.size() &&
19480          "canonicalizeShuffleMaskWithHorizOp "
19481          "shouldn't alter the shuffle mask size");
19482 
19483   // Commute the shuffle if it will improve canonicalization.
19484   if (canonicalizeShuffleMaskWithCommute(Mask)) {
19485     ShuffleVectorSDNode::commuteMask(Mask);
19486     std::swap(V1, V2);
19487   }
19488 
19489   // For each vector width, delegate to a specialized lowering routine.
19490   if (VT.is128BitVector())
19491     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19492 
19493   if (VT.is256BitVector())
19494     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19495 
19496   if (VT.is512BitVector())
19497     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19498 
19499   if (Is1BitVector)
19500     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19501 
19502   llvm_unreachable("Unimplemented!");
19503 }
19504 
19505 /// Try to lower a VSELECT instruction to a vector shuffle.
19506 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
19507                                            const X86Subtarget &Subtarget,
19508                                            SelectionDAG &DAG) {
19509   SDValue Cond = Op.getOperand(0);
19510   SDValue LHS = Op.getOperand(1);
19511   SDValue RHS = Op.getOperand(2);
19512   MVT VT = Op.getSimpleValueType();
19513 
19514   // Only non-legal VSELECTs reach this lowering, convert those into generic
19515   // shuffles and re-use the shuffle lowering path for blends.
19516   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
19517     SmallVector<int, 32> Mask;
19518     if (createShuffleMaskFromVSELECT(Mask, Cond))
19519       return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
19520   }
19521 
19522   return SDValue();
19523 }
19524 
19525 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
19526   SDValue Cond = Op.getOperand(0);
19527   SDValue LHS = Op.getOperand(1);
19528   SDValue RHS = Op.getOperand(2);
19529 
19530   SDLoc dl(Op);
19531   MVT VT = Op.getSimpleValueType();
19532   if (isSoftFP16(VT)) {
19533     MVT NVT = VT.changeVectorElementTypeToInteger();
19534     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
19535                                           DAG.getBitcast(NVT, LHS),
19536                                           DAG.getBitcast(NVT, RHS)));
19537   }
19538 
19539   // A vselect where all conditions and data are constants can be optimized into
19540   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
19541   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
19542       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
19543       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
19544     return SDValue();
19545 
19546   // Try to lower this to a blend-style vector shuffle. This can handle all
19547   // constant condition cases.
19548   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
19549     return BlendOp;
19550 
19551   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
19552   // with patterns on the mask registers on AVX-512.
19553   MVT CondVT = Cond.getSimpleValueType();
19554   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
19555   if (CondEltSize == 1)
19556     return Op;
19557 
19558   // Variable blends are only legal from SSE4.1 onward.
19559   if (!Subtarget.hasSSE41())
19560     return SDValue();
19561 
19562   unsigned EltSize = VT.getScalarSizeInBits();
19563   unsigned NumElts = VT.getVectorNumElements();
19564 
19565   // Expand v32i16/v64i8 without BWI.
19566   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
19567     return SDValue();
19568 
19569   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
19570   // into an i1 condition so that we can use the mask-based 512-bit blend
19571   // instructions.
19572   if (VT.getSizeInBits() == 512) {
19573     // Build a mask by testing the condition against zero.
19574     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
19575     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
19576                                 DAG.getConstant(0, dl, CondVT),
19577                                 ISD::SETNE);
19578     // Now return a new VSELECT using the mask.
19579     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
19580   }
19581 
19582   // SEXT/TRUNC cases where the mask doesn't match the destination size.
19583   if (CondEltSize != EltSize) {
19584     // If we don't have a sign splat, rely on the expansion.
19585     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
19586       return SDValue();
19587 
19588     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
19589     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
19590     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
19591     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
19592   }
19593 
19594   // Only some types will be legal on some subtargets. If we can emit a legal
19595   // VSELECT-matching blend, return Op, and but if we need to expand, return
19596   // a null value.
19597   switch (VT.SimpleTy) {
19598   default:
19599     // Most of the vector types have blends past SSE4.1.
19600     return Op;
19601 
19602   case MVT::v32i8:
19603     // The byte blends for AVX vectors were introduced only in AVX2.
19604     if (Subtarget.hasAVX2())
19605       return Op;
19606 
19607     return SDValue();
19608 
19609   case MVT::v8i16:
19610   case MVT::v16i16: {
19611     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
19612     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
19613     Cond = DAG.getBitcast(CastVT, Cond);
19614     LHS = DAG.getBitcast(CastVT, LHS);
19615     RHS = DAG.getBitcast(CastVT, RHS);
19616     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
19617     return DAG.getBitcast(VT, Select);
19618   }
19619   }
19620 }
19621 
19622 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
19623   MVT VT = Op.getSimpleValueType();
19624   SDValue Vec = Op.getOperand(0);
19625   SDValue Idx = Op.getOperand(1);
19626   assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
19627   SDLoc dl(Op);
19628 
19629   if (!Vec.getSimpleValueType().is128BitVector())
19630     return SDValue();
19631 
19632   if (VT.getSizeInBits() == 8) {
19633     // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
19634     // we're going to zero extend the register or fold the store.
19635     if (llvm::isNullConstant(Idx) && !X86::mayFoldIntoZeroExtend(Op) &&
19636         !X86::mayFoldIntoStore(Op))
19637       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
19638                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19639                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
19640 
19641     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
19642     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
19643                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19644     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19645   }
19646 
19647   if (VT == MVT::f32) {
19648     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
19649     // the result back to FR32 register. It's only worth matching if the
19650     // result has a single use which is a store or a bitcast to i32.  And in
19651     // the case of a store, it's not worth it if the index is a constant 0,
19652     // because a MOVSSmr can be used instead, which is smaller and faster.
19653     if (!Op.hasOneUse())
19654       return SDValue();
19655     SDNode *User = *Op.getNode()->use_begin();
19656     if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
19657         (User->getOpcode() != ISD::BITCAST ||
19658          User->getValueType(0) != MVT::i32))
19659       return SDValue();
19660     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19661                                   DAG.getBitcast(MVT::v4i32, Vec), Idx);
19662     return DAG.getBitcast(MVT::f32, Extract);
19663   }
19664 
19665   if (VT == MVT::i32 || VT == MVT::i64)
19666       return Op;
19667 
19668   return SDValue();
19669 }
19670 
19671 /// Extract one bit from mask vector, like v16i1 or v8i1.
19672 /// AVX-512 feature.
19673 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
19674                                         const X86Subtarget &Subtarget) {
19675   SDValue Vec = Op.getOperand(0);
19676   SDLoc dl(Vec);
19677   MVT VecVT = Vec.getSimpleValueType();
19678   SDValue Idx = Op.getOperand(1);
19679   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19680   MVT EltVT = Op.getSimpleValueType();
19681 
19682   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
19683          "Unexpected vector type in ExtractBitFromMaskVector");
19684 
19685   // variable index can't be handled in mask registers,
19686   // extend vector to VR512/128
19687   if (!IdxC) {
19688     unsigned NumElts = VecVT.getVectorNumElements();
19689     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
19690     // than extending to 128/256bit.
19691     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19692     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19693     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
19694     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
19695     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
19696   }
19697 
19698   unsigned IdxVal = IdxC->getZExtValue();
19699   if (IdxVal == 0) // the operation is legal
19700     return Op;
19701 
19702   // Extend to natively supported kshift.
19703   unsigned NumElems = VecVT.getVectorNumElements();
19704   MVT WideVecVT = VecVT;
19705   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
19706     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19707     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
19708                       DAG.getUNDEF(WideVecVT), Vec,
19709                       DAG.getIntPtrConstant(0, dl));
19710   }
19711 
19712   // Use kshiftr instruction to move to the lower element.
19713   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
19714                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19715 
19716   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19717                      DAG.getIntPtrConstant(0, dl));
19718 }
19719 
19720 SDValue
19721 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
19722                                            SelectionDAG &DAG) const {
19723   SDLoc dl(Op);
19724   SDValue Vec = Op.getOperand(0);
19725   MVT VecVT = Vec.getSimpleValueType();
19726   SDValue Idx = Op.getOperand(1);
19727   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19728 
19729   if (VecVT.getVectorElementType() == MVT::i1)
19730     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
19731 
19732   if (!IdxC) {
19733     // Its more profitable to go through memory (1 cycles throughput)
19734     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
19735     // IACA tool was used to get performance estimation
19736     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
19737     //
19738     // example : extractelement <16 x i8> %a, i32 %i
19739     //
19740     // Block Throughput: 3.00 Cycles
19741     // Throughput Bottleneck: Port5
19742     //
19743     // | Num Of |   Ports pressure in cycles  |    |
19744     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
19745     // ---------------------------------------------
19746     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
19747     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
19748     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
19749     // Total Num Of Uops: 4
19750     //
19751     //
19752     // Block Throughput: 1.00 Cycles
19753     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
19754     //
19755     // |    |  Ports pressure in cycles   |  |
19756     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
19757     // ---------------------------------------------------------
19758     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
19759     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
19760     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
19761     // Total Num Of Uops: 4
19762 
19763     return SDValue();
19764   }
19765 
19766   unsigned IdxVal = IdxC->getZExtValue();
19767 
19768   // If this is a 256-bit vector result, first extract the 128-bit vector and
19769   // then extract the element from the 128-bit vector.
19770   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
19771     // Get the 128-bit vector.
19772     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
19773     MVT EltVT = VecVT.getVectorElementType();
19774 
19775     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
19776     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
19777 
19778     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
19779     // this can be done with a mask.
19780     IdxVal &= ElemsPerChunk - 1;
19781     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19782                        DAG.getIntPtrConstant(IdxVal, dl));
19783   }
19784 
19785   assert(VecVT.is128BitVector() && "Unexpected vector length");
19786 
19787   MVT VT = Op.getSimpleValueType();
19788 
19789   if (VT == MVT::i16) {
19790     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
19791     // we're going to zero extend the register or fold the store (SSE41 only).
19792     if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
19793         !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
19794       if (Subtarget.hasFP16())
19795         return Op;
19796 
19797       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
19798                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19799                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
19800     }
19801 
19802     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
19803                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19804     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19805   }
19806 
19807   if (Subtarget.hasSSE41())
19808     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
19809       return Res;
19810 
19811   // TODO: We only extract a single element from v16i8, we can probably afford
19812   // to be more aggressive here before using the default approach of spilling to
19813   // stack.
19814   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
19815     // Extract either the lowest i32 or any i16, and extract the sub-byte.
19816     int DWordIdx = IdxVal / 4;
19817     if (DWordIdx == 0) {
19818       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19819                                 DAG.getBitcast(MVT::v4i32, Vec),
19820                                 DAG.getIntPtrConstant(DWordIdx, dl));
19821       int ShiftVal = (IdxVal % 4) * 8;
19822       if (ShiftVal != 0)
19823         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
19824                           DAG.getConstant(ShiftVal, dl, MVT::i8));
19825       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19826     }
19827 
19828     int WordIdx = IdxVal / 2;
19829     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
19830                               DAG.getBitcast(MVT::v8i16, Vec),
19831                               DAG.getIntPtrConstant(WordIdx, dl));
19832     int ShiftVal = (IdxVal % 2) * 8;
19833     if (ShiftVal != 0)
19834       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
19835                         DAG.getConstant(ShiftVal, dl, MVT::i8));
19836     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19837   }
19838 
19839   if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
19840     if (IdxVal == 0)
19841       return Op;
19842 
19843     // Shuffle the element to the lowest element, then movss or movsh.
19844     SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
19845     Mask[0] = static_cast<int>(IdxVal);
19846     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19847     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19848                        DAG.getIntPtrConstant(0, dl));
19849   }
19850 
19851   if (VT.getSizeInBits() == 64) {
19852     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
19853     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
19854     //        to match extract_elt for f64.
19855     if (IdxVal == 0)
19856       return Op;
19857 
19858     // UNPCKHPD the element to the lowest double word, then movsd.
19859     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
19860     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
19861     int Mask[2] = { 1, -1 };
19862     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19863     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19864                        DAG.getIntPtrConstant(0, dl));
19865   }
19866 
19867   return SDValue();
19868 }
19869 
19870 /// Insert one bit to mask vector, like v16i1 or v8i1.
19871 /// AVX-512 feature.
19872 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
19873                                      const X86Subtarget &Subtarget) {
19874   SDLoc dl(Op);
19875   SDValue Vec = Op.getOperand(0);
19876   SDValue Elt = Op.getOperand(1);
19877   SDValue Idx = Op.getOperand(2);
19878   MVT VecVT = Vec.getSimpleValueType();
19879 
19880   if (!isa<ConstantSDNode>(Idx)) {
19881     // Non constant index. Extend source and destination,
19882     // insert element and then truncate the result.
19883     unsigned NumElts = VecVT.getVectorNumElements();
19884     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19885     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19886     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
19887       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
19888       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
19889     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
19890   }
19891 
19892   // Copy into a k-register, extract to v1i1 and insert_subvector.
19893   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
19894   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
19895 }
19896 
19897 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
19898                                                   SelectionDAG &DAG) const {
19899   MVT VT = Op.getSimpleValueType();
19900   MVT EltVT = VT.getVectorElementType();
19901   unsigned NumElts = VT.getVectorNumElements();
19902   unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
19903 
19904   if (EltVT == MVT::i1)
19905     return InsertBitToMaskVector(Op, DAG, Subtarget);
19906 
19907   SDLoc dl(Op);
19908   SDValue N0 = Op.getOperand(0);
19909   SDValue N1 = Op.getOperand(1);
19910   SDValue N2 = Op.getOperand(2);
19911   auto *N2C = dyn_cast<ConstantSDNode>(N2);
19912 
19913   if (!N2C) {
19914     // Variable insertion indices, usually we're better off spilling to stack,
19915     // but AVX512 can use a variable compare+select by comparing against all
19916     // possible vector indices, and FP insertion has less gpr->simd traffic.
19917     if (!(Subtarget.hasBWI() ||
19918           (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
19919           (Subtarget.hasSSE41() && VT.isFloatingPoint())))
19920       return SDValue();
19921 
19922     MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
19923     MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
19924     if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
19925       return SDValue();
19926 
19927     SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
19928     SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
19929     SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
19930 
19931     SmallVector<SDValue, 16> RawIndices;
19932     for (unsigned I = 0; I != NumElts; ++I)
19933       RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
19934     SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
19935 
19936     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
19937     return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
19938                            ISD::CondCode::SETEQ);
19939   }
19940 
19941   if (N2C->getAPIntValue().uge(NumElts))
19942     return SDValue();
19943   uint64_t IdxVal = N2C->getZExtValue();
19944 
19945   bool IsZeroElt = X86::isZeroNode(N1);
19946   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
19947 
19948   if (IsZeroElt || IsAllOnesElt) {
19949     // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
19950     // We don't deal with i8 0 since it appears to be handled elsewhere.
19951     if (IsAllOnesElt &&
19952         ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
19953          ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
19954       SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
19955       SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
19956       SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
19957       CstVectorElts[IdxVal] = OnesCst;
19958       SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
19959       return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
19960     }
19961     // See if we can do this more efficiently with a blend shuffle with a
19962     // rematerializable vector.
19963     if (Subtarget.hasSSE41() &&
19964         (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
19965       SmallVector<int, 8> BlendMask;
19966       for (unsigned i = 0; i != NumElts; ++i)
19967         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19968       SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
19969                                     : getOnesVector(VT, DAG, dl);
19970       return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
19971     }
19972   }
19973 
19974   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
19975   // into that, and then insert the subvector back into the result.
19976   if (VT.is256BitVector() || VT.is512BitVector()) {
19977     // With a 256-bit vector, we can insert into the zero element efficiently
19978     // using a blend if we have AVX or AVX2 and the right data type.
19979     if (VT.is256BitVector() && IdxVal == 0) {
19980       // TODO: It is worthwhile to cast integer to floating point and back
19981       // and incur a domain crossing penalty if that's what we'll end up
19982       // doing anyway after extracting to a 128-bit vector.
19983       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
19984           (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
19985         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19986         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
19987                            DAG.getTargetConstant(1, dl, MVT::i8));
19988       }
19989     }
19990 
19991     unsigned NumEltsIn128 = 128 / EltSizeInBits;
19992     assert(isPowerOf2_32(NumEltsIn128) &&
19993            "Vectors will always have power-of-two number of elements.");
19994 
19995     // If we are not inserting into the low 128-bit vector chunk,
19996     // then prefer the broadcast+blend sequence.
19997     // FIXME: relax the profitability check iff all N1 uses are insertions.
19998     if (IdxVal >= NumEltsIn128 &&
19999         ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
20000          (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
20001           X86::mayFoldLoad(N1, Subtarget)))) {
20002       SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
20003       SmallVector<int, 8> BlendMask;
20004       for (unsigned i = 0; i != NumElts; ++i)
20005         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
20006       return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
20007     }
20008 
20009     // Get the desired 128-bit vector chunk.
20010     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
20011 
20012     // Insert the element into the desired chunk.
20013     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
20014     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
20015 
20016     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
20017                     DAG.getIntPtrConstant(IdxIn128, dl));
20018 
20019     // Insert the changed part back into the bigger vector
20020     return insert128BitVector(N0, V, IdxVal, DAG, dl);
20021   }
20022   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
20023 
20024   // This will be just movw/movd/movq/movsh/movss/movsd.
20025   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
20026     if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
20027         EltVT == MVT::f16 || EltVT == MVT::i64) {
20028       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
20029       return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
20030     }
20031 
20032     // We can't directly insert an i8 or i16 into a vector, so zero extend
20033     // it to i32 first.
20034     if (EltVT == MVT::i16 || EltVT == MVT::i8) {
20035       N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
20036       MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
20037       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
20038       N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
20039       return DAG.getBitcast(VT, N1);
20040     }
20041   }
20042 
20043   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
20044   // argument. SSE41 required for pinsrb.
20045   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
20046     unsigned Opc;
20047     if (VT == MVT::v8i16) {
20048       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
20049       Opc = X86ISD::PINSRW;
20050     } else {
20051       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
20052       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
20053       Opc = X86ISD::PINSRB;
20054     }
20055 
20056     assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
20057     N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
20058     N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
20059     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
20060   }
20061 
20062   if (Subtarget.hasSSE41()) {
20063     if (EltVT == MVT::f32) {
20064       // Bits [7:6] of the constant are the source select. This will always be
20065       //   zero here. The DAG Combiner may combine an extract_elt index into
20066       //   these bits. For example (insert (extract, 3), 2) could be matched by
20067       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
20068       // Bits [5:4] of the constant are the destination select. This is the
20069       //   value of the incoming immediate.
20070       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
20071       //   combine either bitwise AND or insert of float 0.0 to set these bits.
20072 
20073       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
20074       if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
20075         // If this is an insertion of 32-bits into the low 32-bits of
20076         // a vector, we prefer to generate a blend with immediate rather
20077         // than an insertps. Blends are simpler operations in hardware and so
20078         // will always have equal or better performance than insertps.
20079         // But if optimizing for size and there's a load folding opportunity,
20080         // generate insertps because blendps does not have a 32-bit memory
20081         // operand form.
20082         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
20083         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
20084                            DAG.getTargetConstant(1, dl, MVT::i8));
20085       }
20086       // Create this as a scalar to vector..
20087       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
20088       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
20089                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
20090     }
20091 
20092     // PINSR* works with constant index.
20093     if (EltVT == MVT::i32 || EltVT == MVT::i64)
20094       return Op;
20095   }
20096 
20097   return SDValue();
20098 }
20099 
20100 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
20101                                      SelectionDAG &DAG) {
20102   SDLoc dl(Op);
20103   MVT OpVT = Op.getSimpleValueType();
20104 
20105   // It's always cheaper to replace a xor+movd with xorps and simplifies further
20106   // combines.
20107   if (X86::isZeroNode(Op.getOperand(0)))
20108     return getZeroVector(OpVT, Subtarget, DAG, dl);
20109 
20110   // If this is a 256-bit vector result, first insert into a 128-bit
20111   // vector and then insert into the 256-bit vector.
20112   if (!OpVT.is128BitVector()) {
20113     // Insert into a 128-bit vector.
20114     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
20115     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
20116                                  OpVT.getVectorNumElements() / SizeFactor);
20117 
20118     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
20119 
20120     // Insert the 128-bit vector.
20121     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
20122   }
20123   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
20124          "Expected an SSE type!");
20125 
20126   // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
20127   // tblgen.
20128   if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
20129     return Op;
20130 
20131   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
20132   return DAG.getBitcast(
20133       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
20134 }
20135 
20136 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
20137 // simple superregister reference or explicit instructions to insert
20138 // the upper bits of a vector.
20139 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
20140                                      SelectionDAG &DAG) {
20141   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
20142 
20143   return insert1BitVector(Op, DAG, Subtarget);
20144 }
20145 
20146 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
20147                                       SelectionDAG &DAG) {
20148   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
20149          "Only vXi1 extract_subvectors need custom lowering");
20150 
20151   SDLoc dl(Op);
20152   SDValue Vec = Op.getOperand(0);
20153   uint64_t IdxVal = Op.getConstantOperandVal(1);
20154 
20155   if (IdxVal == 0) // the operation is legal
20156     return Op;
20157 
20158   MVT VecVT = Vec.getSimpleValueType();
20159   unsigned NumElems = VecVT.getVectorNumElements();
20160 
20161   // Extend to natively supported kshift.
20162   MVT WideVecVT = VecVT;
20163   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
20164     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
20165     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
20166                       DAG.getUNDEF(WideVecVT), Vec,
20167                       DAG.getIntPtrConstant(0, dl));
20168   }
20169 
20170   // Shift to the LSB.
20171   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
20172                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
20173 
20174   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
20175                      DAG.getIntPtrConstant(0, dl));
20176 }
20177 
20178 // Returns the appropriate wrapper opcode for a global reference.
20179 unsigned X86TargetLowering::getGlobalWrapperKind(
20180     const GlobalValue *GV, const unsigned char OpFlags) const {
20181   // References to absolute symbols are never PC-relative.
20182   if (GV && GV->isAbsoluteSymbolRef())
20183     return X86ISD::Wrapper;
20184 
20185   CodeModel::Model M = getTargetMachine().getCodeModel();
20186   if (Subtarget.isPICStyleRIPRel() &&
20187       (M == CodeModel::Small || M == CodeModel::Kernel))
20188     return X86ISD::WrapperRIP;
20189 
20190   // GOTPCREL references must always use RIP.
20191   if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
20192     return X86ISD::WrapperRIP;
20193 
20194   return X86ISD::Wrapper;
20195 }
20196 
20197 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
20198 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
20199 // one of the above mentioned nodes. It has to be wrapped because otherwise
20200 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
20201 // be used to form addressing mode. These wrapped nodes will be selected
20202 // into MOV32ri.
20203 SDValue
20204 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
20205   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
20206 
20207   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20208   // global base reg.
20209   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
20210 
20211   auto PtrVT = getPointerTy(DAG.getDataLayout());
20212   SDValue Result = DAG.getTargetConstantPool(
20213       CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
20214   SDLoc DL(CP);
20215   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
20216   // With PIC, the address is actually $g + Offset.
20217   if (OpFlag) {
20218     Result =
20219         DAG.getNode(ISD::ADD, DL, PtrVT,
20220                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
20221   }
20222 
20223   return Result;
20224 }
20225 
20226 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
20227   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
20228 
20229   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20230   // global base reg.
20231   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
20232 
20233   auto PtrVT = getPointerTy(DAG.getDataLayout());
20234   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
20235   SDLoc DL(JT);
20236   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
20237 
20238   // With PIC, the address is actually $g + Offset.
20239   if (OpFlag)
20240     Result =
20241         DAG.getNode(ISD::ADD, DL, PtrVT,
20242                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
20243 
20244   return Result;
20245 }
20246 
20247 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
20248                                                SelectionDAG &DAG) const {
20249   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
20250 }
20251 
20252 SDValue
20253 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
20254   // Create the TargetBlockAddressAddress node.
20255   unsigned char OpFlags =
20256     Subtarget.classifyBlockAddressReference();
20257   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
20258   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
20259   SDLoc dl(Op);
20260   auto PtrVT = getPointerTy(DAG.getDataLayout());
20261   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
20262   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
20263 
20264   // With PIC, the address is actually $g + Offset.
20265   if (isGlobalRelativeToPICBase(OpFlags)) {
20266     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
20267                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
20268   }
20269 
20270   return Result;
20271 }
20272 
20273 /// Creates target global address or external symbol nodes for calls or
20274 /// other uses.
20275 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
20276                                                  bool ForCall) const {
20277   // Unpack the global address or external symbol.
20278   const SDLoc &dl = SDLoc(Op);
20279   const GlobalValue *GV = nullptr;
20280   int64_t Offset = 0;
20281   const char *ExternalSym = nullptr;
20282   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
20283     GV = G->getGlobal();
20284     Offset = G->getOffset();
20285   } else {
20286     const auto *ES = cast<ExternalSymbolSDNode>(Op);
20287     ExternalSym = ES->getSymbol();
20288   }
20289 
20290   // Calculate some flags for address lowering.
20291   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
20292   unsigned char OpFlags;
20293   if (ForCall)
20294     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
20295   else
20296     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
20297   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
20298   bool NeedsLoad = isGlobalStubReference(OpFlags);
20299 
20300   CodeModel::Model M = DAG.getTarget().getCodeModel();
20301   auto PtrVT = getPointerTy(DAG.getDataLayout());
20302   SDValue Result;
20303 
20304   if (GV) {
20305     // Create a target global address if this is a global. If possible, fold the
20306     // offset into the global address reference. Otherwise, ADD it on later.
20307     // Suppress the folding if Offset is negative: movl foo-1, %eax is not
20308     // allowed because if the address of foo is 0, the ELF R_X86_64_32
20309     // relocation will compute to a negative value, which is invalid.
20310     int64_t GlobalOffset = 0;
20311     if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
20312         X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
20313       std::swap(GlobalOffset, Offset);
20314     }
20315     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
20316   } else {
20317     // If this is not a global address, this must be an external symbol.
20318     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
20319   }
20320 
20321   // If this is a direct call, avoid the wrapper if we don't need to do any
20322   // loads or adds. This allows SDAG ISel to match direct calls.
20323   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
20324     return Result;
20325 
20326   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
20327 
20328   // With PIC, the address is actually $g + Offset.
20329   if (HasPICReg) {
20330     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
20331                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
20332   }
20333 
20334   // For globals that require a load from a stub to get the address, emit the
20335   // load.
20336   if (NeedsLoad)
20337     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
20338                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
20339 
20340   // If there was a non-zero offset that we didn't fold, create an explicit
20341   // addition for it.
20342   if (Offset != 0)
20343     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
20344                          DAG.getConstant(Offset, dl, PtrVT));
20345 
20346   return Result;
20347 }
20348 
20349 SDValue
20350 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
20351   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
20352 }
20353 
20354 static SDValue
20355 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
20356            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
20357            unsigned char OperandFlags, bool LocalDynamic = false) {
20358   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
20359   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20360   SDLoc dl(GA);
20361   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20362                                            GA->getValueType(0),
20363                                            GA->getOffset(),
20364                                            OperandFlags);
20365 
20366   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
20367                                            : X86ISD::TLSADDR;
20368 
20369   if (InFlag) {
20370     SDValue Ops[] = { Chain,  TGA, *InFlag };
20371     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
20372   } else {
20373     SDValue Ops[]  = { Chain, TGA };
20374     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
20375   }
20376 
20377   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
20378   MFI.setAdjustsStack(true);
20379   MFI.setHasCalls(true);
20380 
20381   SDValue Flag = Chain.getValue(1);
20382   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
20383 }
20384 
20385 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
20386 static SDValue
20387 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
20388                                 const EVT PtrVT) {
20389   SDValue InFlag;
20390   SDLoc dl(GA);  // ? function entry point might be better
20391   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
20392                                    DAG.getNode(X86ISD::GlobalBaseReg,
20393                                                SDLoc(), PtrVT), InFlag);
20394   InFlag = Chain.getValue(1);
20395 
20396   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
20397 }
20398 
20399 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
20400 static SDValue
20401 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
20402                                 const EVT PtrVT) {
20403   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
20404                     X86::RAX, X86II::MO_TLSGD);
20405 }
20406 
20407 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
20408 static SDValue
20409 LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
20410                                  const EVT PtrVT) {
20411   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
20412                     X86::EAX, X86II::MO_TLSGD);
20413 }
20414 
20415 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
20416                                            SelectionDAG &DAG, const EVT PtrVT,
20417                                            bool Is64Bit, bool Is64BitLP64) {
20418   SDLoc dl(GA);
20419 
20420   // Get the start address of the TLS block for this module.
20421   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
20422       .getInfo<X86MachineFunctionInfo>();
20423   MFI->incNumLocalDynamicTLSAccesses();
20424 
20425   SDValue Base;
20426   if (Is64Bit) {
20427     unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
20428     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, ReturnReg,
20429                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
20430   } else {
20431     SDValue InFlag;
20432     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
20433         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
20434     InFlag = Chain.getValue(1);
20435     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
20436                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
20437   }
20438 
20439   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
20440   // of Base.
20441 
20442   // Build x@dtpoff.
20443   unsigned char OperandFlags = X86II::MO_DTPOFF;
20444   unsigned WrapperKind = X86ISD::Wrapper;
20445   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20446                                            GA->getValueType(0),
20447                                            GA->getOffset(), OperandFlags);
20448   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20449 
20450   // Add x@dtpoff with the base.
20451   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
20452 }
20453 
20454 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
20455 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
20456                                    const EVT PtrVT, TLSModel::Model model,
20457                                    bool is64Bit, bool isPIC) {
20458   SDLoc dl(GA);
20459 
20460   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
20461   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
20462                                                          is64Bit ? 257 : 256));
20463 
20464   SDValue ThreadPointer =
20465       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
20466                   MachinePointerInfo(Ptr));
20467 
20468   unsigned char OperandFlags = 0;
20469   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
20470   // initialexec.
20471   unsigned WrapperKind = X86ISD::Wrapper;
20472   if (model == TLSModel::LocalExec) {
20473     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
20474   } else if (model == TLSModel::InitialExec) {
20475     if (is64Bit) {
20476       OperandFlags = X86II::MO_GOTTPOFF;
20477       WrapperKind = X86ISD::WrapperRIP;
20478     } else {
20479       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
20480     }
20481   } else {
20482     llvm_unreachable("Unexpected model");
20483   }
20484 
20485   // emit "addl x@ntpoff,%eax" (local exec)
20486   // or "addl x@indntpoff,%eax" (initial exec)
20487   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
20488   SDValue TGA =
20489       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
20490                                  GA->getOffset(), OperandFlags);
20491   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20492 
20493   if (model == TLSModel::InitialExec) {
20494     if (isPIC && !is64Bit) {
20495       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
20496                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20497                            Offset);
20498     }
20499 
20500     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
20501                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
20502   }
20503 
20504   // The address of the thread local variable is the add of the thread
20505   // pointer with the offset of the variable.
20506   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
20507 }
20508 
20509 SDValue
20510 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
20511 
20512   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
20513 
20514   if (DAG.getTarget().useEmulatedTLS())
20515     return LowerToTLSEmulatedModel(GA, DAG);
20516 
20517   const GlobalValue *GV = GA->getGlobal();
20518   auto PtrVT = getPointerTy(DAG.getDataLayout());
20519   bool PositionIndependent = isPositionIndependent();
20520 
20521   if (Subtarget.isTargetELF()) {
20522     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
20523     switch (model) {
20524       case TLSModel::GeneralDynamic:
20525         if (Subtarget.is64Bit()) {
20526           if (Subtarget.isTarget64BitLP64())
20527             return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
20528           return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
20529         }
20530         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
20531       case TLSModel::LocalDynamic:
20532         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
20533                                            Subtarget.isTarget64BitLP64());
20534       case TLSModel::InitialExec:
20535       case TLSModel::LocalExec:
20536         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
20537                                    PositionIndependent);
20538     }
20539     llvm_unreachable("Unknown TLS model.");
20540   }
20541 
20542   if (Subtarget.isTargetDarwin()) {
20543     // Darwin only has one model of TLS.  Lower to that.
20544     unsigned char OpFlag = 0;
20545     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
20546                            X86ISD::WrapperRIP : X86ISD::Wrapper;
20547 
20548     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20549     // global base reg.
20550     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
20551     if (PIC32)
20552       OpFlag = X86II::MO_TLVP_PIC_BASE;
20553     else
20554       OpFlag = X86II::MO_TLVP;
20555     SDLoc DL(Op);
20556     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
20557                                                 GA->getValueType(0),
20558                                                 GA->getOffset(), OpFlag);
20559     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
20560 
20561     // With PIC32, the address is actually $g + Offset.
20562     if (PIC32)
20563       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
20564                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20565                            Offset);
20566 
20567     // Lowering the machine isd will make sure everything is in the right
20568     // location.
20569     SDValue Chain = DAG.getEntryNode();
20570     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20571     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
20572     SDValue Args[] = { Chain, Offset };
20573     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
20574     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
20575                                DAG.getIntPtrConstant(0, DL, true),
20576                                Chain.getValue(1), DL);
20577 
20578     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
20579     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
20580     MFI.setAdjustsStack(true);
20581 
20582     // And our return value (tls address) is in the standard call return value
20583     // location.
20584     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
20585     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
20586   }
20587 
20588   if (Subtarget.isOSWindows()) {
20589     // Just use the implicit TLS architecture
20590     // Need to generate something similar to:
20591     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
20592     //                                  ; from TEB
20593     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
20594     //   mov     rcx, qword [rdx+rcx*8]
20595     //   mov     eax, .tls$:tlsvar
20596     //   [rax+rcx] contains the address
20597     // Windows 64bit: gs:0x58
20598     // Windows 32bit: fs:__tls_array
20599 
20600     SDLoc dl(GA);
20601     SDValue Chain = DAG.getEntryNode();
20602 
20603     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
20604     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
20605     // use its literal value of 0x2C.
20606     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
20607                                         ? Type::getInt8PtrTy(*DAG.getContext(),
20608                                                              256)
20609                                         : Type::getInt32PtrTy(*DAG.getContext(),
20610                                                               257));
20611 
20612     SDValue TlsArray = Subtarget.is64Bit()
20613                            ? DAG.getIntPtrConstant(0x58, dl)
20614                            : (Subtarget.isTargetWindowsGNU()
20615                                   ? DAG.getIntPtrConstant(0x2C, dl)
20616                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
20617 
20618     SDValue ThreadPointer =
20619         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
20620 
20621     SDValue res;
20622     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
20623       res = ThreadPointer;
20624     } else {
20625       // Load the _tls_index variable
20626       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
20627       if (Subtarget.is64Bit())
20628         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
20629                              MachinePointerInfo(), MVT::i32);
20630       else
20631         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
20632 
20633       const DataLayout &DL = DAG.getDataLayout();
20634       SDValue Scale =
20635           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
20636       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
20637 
20638       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
20639     }
20640 
20641     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
20642 
20643     // Get the offset of start of .tls section
20644     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20645                                              GA->getValueType(0),
20646                                              GA->getOffset(), X86II::MO_SECREL);
20647     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
20648 
20649     // The address of the thread local variable is the add of the thread
20650     // pointer with the offset of the variable.
20651     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
20652   }
20653 
20654   llvm_unreachable("TLS not implemented for this target.");
20655 }
20656 
20657 /// Lower SRA_PARTS and friends, which return two i32 values
20658 /// and take a 2 x i32 value to shift plus a shift amount.
20659 /// TODO: Can this be moved to general expansion code?
20660 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
20661   SDValue Lo, Hi;
20662   DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
20663   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
20664 }
20665 
20666 // Try to use a packed vector operation to handle i64 on 32-bit targets when
20667 // AVX512DQ is enabled.
20668 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
20669                                         const X86Subtarget &Subtarget) {
20670   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20671           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20672           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20673           Op.getOpcode() == ISD::UINT_TO_FP) &&
20674          "Unexpected opcode!");
20675   bool IsStrict = Op->isStrictFPOpcode();
20676   unsigned OpNo = IsStrict ? 1 : 0;
20677   SDValue Src = Op.getOperand(OpNo);
20678   MVT SrcVT = Src.getSimpleValueType();
20679   MVT VT = Op.getSimpleValueType();
20680 
20681    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
20682        (VT != MVT::f32 && VT != MVT::f64))
20683     return SDValue();
20684 
20685   // Pack the i64 into a vector, do the operation and extract.
20686 
20687   // Using 256-bit to ensure result is 128-bits for f32 case.
20688   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
20689   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
20690   MVT VecVT = MVT::getVectorVT(VT, NumElts);
20691 
20692   SDLoc dl(Op);
20693   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
20694   if (IsStrict) {
20695     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
20696                                  {Op.getOperand(0), InVec});
20697     SDValue Chain = CvtVec.getValue(1);
20698     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20699                                 DAG.getIntPtrConstant(0, dl));
20700     return DAG.getMergeValues({Value, Chain}, dl);
20701   }
20702 
20703   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
20704 
20705   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20706                      DAG.getIntPtrConstant(0, dl));
20707 }
20708 
20709 // Try to use a packed vector operation to handle i64 on 32-bit targets.
20710 static SDValue LowerI64IntToFP16(SDValue Op, SelectionDAG &DAG,
20711                                  const X86Subtarget &Subtarget) {
20712   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20713           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20714           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20715           Op.getOpcode() == ISD::UINT_TO_FP) &&
20716          "Unexpected opcode!");
20717   bool IsStrict = Op->isStrictFPOpcode();
20718   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20719   MVT SrcVT = Src.getSimpleValueType();
20720   MVT VT = Op.getSimpleValueType();
20721 
20722   if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
20723     return SDValue();
20724 
20725   // Pack the i64 into a vector, do the operation and extract.
20726 
20727   assert(Subtarget.hasFP16() && "Expected FP16");
20728 
20729   SDLoc dl(Op);
20730   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
20731   if (IsStrict) {
20732     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
20733                                  {Op.getOperand(0), InVec});
20734     SDValue Chain = CvtVec.getValue(1);
20735     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20736                                 DAG.getIntPtrConstant(0, dl));
20737     return DAG.getMergeValues({Value, Chain}, dl);
20738   }
20739 
20740   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
20741 
20742   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20743                      DAG.getIntPtrConstant(0, dl));
20744 }
20745 
20746 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
20747                           const X86Subtarget &Subtarget) {
20748   switch (Opcode) {
20749     case ISD::SINT_TO_FP:
20750       // TODO: Handle wider types with AVX/AVX512.
20751       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
20752         return false;
20753       // CVTDQ2PS or (V)CVTDQ2PD
20754       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
20755 
20756     case ISD::UINT_TO_FP:
20757       // TODO: Handle wider types and i64 elements.
20758       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
20759         return false;
20760       // VCVTUDQ2PS or VCVTUDQ2PD
20761       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
20762 
20763     default:
20764       return false;
20765   }
20766 }
20767 
20768 /// Given a scalar cast operation that is extracted from a vector, try to
20769 /// vectorize the cast op followed by extraction. This will avoid an expensive
20770 /// round-trip between XMM and GPR.
20771 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
20772                                       const X86Subtarget &Subtarget) {
20773   // TODO: This could be enhanced to handle smaller integer types by peeking
20774   // through an extend.
20775   SDValue Extract = Cast.getOperand(0);
20776   MVT DestVT = Cast.getSimpleValueType();
20777   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20778       !isa<ConstantSDNode>(Extract.getOperand(1)))
20779     return SDValue();
20780 
20781   // See if we have a 128-bit vector cast op for this type of cast.
20782   SDValue VecOp = Extract.getOperand(0);
20783   MVT FromVT = VecOp.getSimpleValueType();
20784   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
20785   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
20786   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
20787   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
20788     return SDValue();
20789 
20790   // If we are extracting from a non-zero element, first shuffle the source
20791   // vector to allow extracting from element zero.
20792   SDLoc DL(Cast);
20793   if (!isNullConstant(Extract.getOperand(1))) {
20794     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
20795     Mask[0] = Extract.getConstantOperandVal(1);
20796     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
20797   }
20798   // If the source vector is wider than 128-bits, extract the low part. Do not
20799   // create an unnecessarily wide vector cast op.
20800   if (FromVT != Vec128VT)
20801     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
20802 
20803   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
20804   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
20805   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
20806   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
20807                      DAG.getIntPtrConstant(0, DL));
20808 }
20809 
20810 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
20811 /// try to vectorize the cast ops. This will avoid an expensive round-trip
20812 /// between XMM and GPR.
20813 static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
20814                                 const X86Subtarget &Subtarget) {
20815   // TODO: Allow FP_TO_UINT.
20816   SDValue CastToInt = CastToFP.getOperand(0);
20817   MVT VT = CastToFP.getSimpleValueType();
20818   if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
20819     return SDValue();
20820 
20821   MVT IntVT = CastToInt.getSimpleValueType();
20822   SDValue X = CastToInt.getOperand(0);
20823   MVT SrcVT = X.getSimpleValueType();
20824   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
20825     return SDValue();
20826 
20827   // See if we have 128-bit vector cast instructions for this type of cast.
20828   // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
20829   if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
20830       IntVT != MVT::i32)
20831     return SDValue();
20832 
20833   unsigned SrcSize = SrcVT.getSizeInBits();
20834   unsigned IntSize = IntVT.getSizeInBits();
20835   unsigned VTSize = VT.getSizeInBits();
20836   MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
20837   MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
20838   MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
20839 
20840   // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
20841   unsigned ToIntOpcode =
20842       SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
20843   unsigned ToFPOpcode =
20844       IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
20845 
20846   // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
20847   //
20848   // We are not defining the high elements (for example, zero them) because
20849   // that could nullify any performance advantage that we hoped to gain from
20850   // this vector op hack. We do not expect any adverse effects (like denorm
20851   // penalties) with cast ops.
20852   SDLoc DL(CastToFP);
20853   SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
20854   SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
20855   SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
20856   SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
20857   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
20858 }
20859 
20860 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
20861                                     const X86Subtarget &Subtarget) {
20862   SDLoc DL(Op);
20863   bool IsStrict = Op->isStrictFPOpcode();
20864   MVT VT = Op->getSimpleValueType(0);
20865   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
20866 
20867   if (Subtarget.hasDQI()) {
20868     assert(!Subtarget.hasVLX() && "Unexpected features");
20869 
20870     assert((Src.getSimpleValueType() == MVT::v2i64 ||
20871             Src.getSimpleValueType() == MVT::v4i64) &&
20872            "Unsupported custom type");
20873 
20874     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
20875     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
20876            "Unexpected VT!");
20877     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20878 
20879     // Need to concat with zero vector for strict fp to avoid spurious
20880     // exceptions.
20881     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
20882                            : DAG.getUNDEF(MVT::v8i64);
20883     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
20884                       DAG.getIntPtrConstant(0, DL));
20885     SDValue Res, Chain;
20886     if (IsStrict) {
20887       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
20888                         {Op->getOperand(0), Src});
20889       Chain = Res.getValue(1);
20890     } else {
20891       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
20892     }
20893 
20894     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20895                       DAG.getIntPtrConstant(0, DL));
20896 
20897     if (IsStrict)
20898       return DAG.getMergeValues({Res, Chain}, DL);
20899     return Res;
20900   }
20901 
20902   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
20903                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
20904   if (VT != MVT::v4f32 || IsSigned)
20905     return SDValue();
20906 
20907   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
20908   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
20909   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
20910                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
20911                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
20912   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
20913   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
20914   SmallVector<SDValue, 4> SignCvts(4);
20915   SmallVector<SDValue, 4> Chains(4);
20916   for (int i = 0; i != 4; ++i) {
20917     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
20918                               DAG.getIntPtrConstant(i, DL));
20919     if (IsStrict) {
20920       SignCvts[i] =
20921           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
20922                       {Op.getOperand(0), Elt});
20923       Chains[i] = SignCvts[i].getValue(1);
20924     } else {
20925       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
20926     }
20927   }
20928   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
20929 
20930   SDValue Slow, Chain;
20931   if (IsStrict) {
20932     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
20933     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
20934                        {Chain, SignCvt, SignCvt});
20935     Chain = Slow.getValue(1);
20936   } else {
20937     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
20938   }
20939 
20940   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
20941   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
20942 
20943   if (IsStrict)
20944     return DAG.getMergeValues({Cvt, Chain}, DL);
20945 
20946   return Cvt;
20947 }
20948 
20949 static SDValue promoteXINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
20950   bool IsStrict = Op->isStrictFPOpcode();
20951   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20952   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20953   MVT VT = Op.getSimpleValueType();
20954   MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
20955   SDLoc dl(Op);
20956 
20957   SDValue Rnd = DAG.getIntPtrConstant(0, dl);
20958   if (IsStrict)
20959     return DAG.getNode(
20960         ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
20961         {Chain,
20962          DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
20963          Rnd});
20964   return DAG.getNode(ISD::FP_ROUND, dl, VT,
20965                      DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
20966 }
20967 
20968 static bool isLegalConversion(MVT VT, bool IsSigned,
20969                               const X86Subtarget &Subtarget) {
20970   if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
20971     return true;
20972   if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
20973     return true;
20974   if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
20975     return true;
20976   if (Subtarget.useAVX512Regs()) {
20977     if (VT == MVT::v16i32)
20978       return true;
20979     if (VT == MVT::v8i64 && Subtarget.hasDQI())
20980       return true;
20981   }
20982   if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
20983       (VT == MVT::v2i64 || VT == MVT::v4i64))
20984     return true;
20985   return false;
20986 }
20987 
20988 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
20989                                            SelectionDAG &DAG) const {
20990   bool IsStrict = Op->isStrictFPOpcode();
20991   unsigned OpNo = IsStrict ? 1 : 0;
20992   SDValue Src = Op.getOperand(OpNo);
20993   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20994   MVT SrcVT = Src.getSimpleValueType();
20995   MVT VT = Op.getSimpleValueType();
20996   SDLoc dl(Op);
20997 
20998   if (isSoftFP16(VT))
20999     return promoteXINT_TO_FP(Op, DAG);
21000   else if (isLegalConversion(SrcVT, true, Subtarget))
21001     return Op;
21002 
21003   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
21004     return LowerWin64_INT128_TO_FP(Op, DAG);
21005 
21006   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
21007     return Extract;
21008 
21009   if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
21010     return R;
21011 
21012   if (SrcVT.isVector()) {
21013     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
21014       // Note: Since v2f64 is a legal type. We don't need to zero extend the
21015       // source for strict FP.
21016       if (IsStrict)
21017         return DAG.getNode(
21018             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
21019             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
21020                                 DAG.getUNDEF(SrcVT))});
21021       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
21022                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
21023                                      DAG.getUNDEF(SrcVT)));
21024     }
21025     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
21026       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
21027 
21028     return SDValue();
21029   }
21030 
21031   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
21032          "Unknown SINT_TO_FP to lower!");
21033 
21034   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
21035 
21036   // These are really Legal; return the operand so the caller accepts it as
21037   // Legal.
21038   if (SrcVT == MVT::i32 && UseSSEReg)
21039     return Op;
21040   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
21041     return Op;
21042 
21043   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
21044     return V;
21045   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
21046     return V;
21047 
21048   // SSE doesn't have an i16 conversion so we need to promote.
21049   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
21050     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
21051     if (IsStrict)
21052       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
21053                          {Chain, Ext});
21054 
21055     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
21056   }
21057 
21058   if (VT == MVT::f128)
21059     return SDValue();
21060 
21061   SDValue ValueToStore = Src;
21062   if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
21063     // Bitcasting to f64 here allows us to do a single 64-bit store from
21064     // an SSE register, avoiding the store forwarding penalty that would come
21065     // with two 32-bit stores.
21066     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
21067 
21068   unsigned Size = SrcVT.getStoreSize();
21069   Align Alignment(Size);
21070   MachineFunction &MF = DAG.getMachineFunction();
21071   auto PtrVT = getPointerTy(MF.getDataLayout());
21072   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
21073   MachinePointerInfo MPI =
21074       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
21075   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
21076   Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
21077   std::pair<SDValue, SDValue> Tmp =
21078       BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
21079 
21080   if (IsStrict)
21081     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
21082 
21083   return Tmp.first;
21084 }
21085 
21086 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
21087     EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
21088     MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
21089   // Build the FILD
21090   SDVTList Tys;
21091   bool useSSE = isScalarFPTypeInSSEReg(DstVT);
21092   if (useSSE)
21093     Tys = DAG.getVTList(MVT::f80, MVT::Other);
21094   else
21095     Tys = DAG.getVTList(DstVT, MVT::Other);
21096 
21097   SDValue FILDOps[] = {Chain, Pointer};
21098   SDValue Result =
21099       DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
21100                               Alignment, MachineMemOperand::MOLoad);
21101   Chain = Result.getValue(1);
21102 
21103   if (useSSE) {
21104     MachineFunction &MF = DAG.getMachineFunction();
21105     unsigned SSFISize = DstVT.getStoreSize();
21106     int SSFI =
21107         MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
21108     auto PtrVT = getPointerTy(MF.getDataLayout());
21109     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
21110     Tys = DAG.getVTList(MVT::Other);
21111     SDValue FSTOps[] = {Chain, Result, StackSlot};
21112     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
21113         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
21114         MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
21115 
21116     Chain =
21117         DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
21118     Result = DAG.getLoad(
21119         DstVT, DL, Chain, StackSlot,
21120         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
21121     Chain = Result.getValue(1);
21122   }
21123 
21124   return { Result, Chain };
21125 }
21126 
21127 /// Horizontal vector math instructions may be slower than normal math with
21128 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
21129 /// implementation, and likely shuffle complexity of the alternate sequence.
21130 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
21131                                   const X86Subtarget &Subtarget) {
21132   bool IsOptimizingSize = DAG.shouldOptForSize();
21133   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
21134   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
21135 }
21136 
21137 /// 64-bit unsigned integer to double expansion.
21138 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
21139                                    const X86Subtarget &Subtarget) {
21140   // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
21141   // when converting 0 when rounding toward negative infinity. Caller will
21142   // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
21143   assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
21144   // This algorithm is not obvious. Here it is what we're trying to output:
21145   /*
21146      movq       %rax,  %xmm0
21147      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
21148      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
21149      #ifdef __SSE3__
21150        haddpd   %xmm0, %xmm0
21151      #else
21152        pshufd   $0x4e, %xmm0, %xmm1
21153        addpd    %xmm1, %xmm0
21154      #endif
21155   */
21156 
21157   SDLoc dl(Op);
21158   LLVMContext *Context = DAG.getContext();
21159 
21160   // Build some magic constants.
21161   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
21162   Constant *C0 = ConstantDataVector::get(*Context, CV0);
21163   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
21164   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
21165 
21166   SmallVector<Constant*,2> CV1;
21167   CV1.push_back(
21168     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
21169                                       APInt(64, 0x4330000000000000ULL))));
21170   CV1.push_back(
21171     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
21172                                       APInt(64, 0x4530000000000000ULL))));
21173   Constant *C1 = ConstantVector::get(CV1);
21174   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
21175 
21176   // Load the 64-bit value into an XMM register.
21177   SDValue XR1 =
21178       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
21179   SDValue CLod0 = DAG.getLoad(
21180       MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
21181       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
21182   SDValue Unpck1 =
21183       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
21184 
21185   SDValue CLod1 = DAG.getLoad(
21186       MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
21187       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
21188   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
21189   // TODO: Are there any fast-math-flags to propagate here?
21190   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
21191   SDValue Result;
21192 
21193   if (Subtarget.hasSSE3() &&
21194       shouldUseHorizontalOp(true, DAG, Subtarget)) {
21195     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
21196   } else {
21197     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
21198     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
21199   }
21200   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
21201                        DAG.getIntPtrConstant(0, dl));
21202   return Result;
21203 }
21204 
21205 /// 32-bit unsigned integer to float expansion.
21206 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
21207                                    const X86Subtarget &Subtarget) {
21208   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
21209   SDLoc dl(Op);
21210   // FP constant to bias correct the final result.
21211   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
21212                                    MVT::f64);
21213 
21214   // Load the 32-bit value into an XMM register.
21215   SDValue Load =
21216       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
21217 
21218   // Zero out the upper parts of the register.
21219   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
21220 
21221   // Or the load with the bias.
21222   SDValue Or = DAG.getNode(
21223       ISD::OR, dl, MVT::v2i64,
21224       DAG.getBitcast(MVT::v2i64, Load),
21225       DAG.getBitcast(MVT::v2i64,
21226                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
21227   Or =
21228       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
21229                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
21230 
21231   if (Op.getNode()->isStrictFPOpcode()) {
21232     // Subtract the bias.
21233     // TODO: Are there any fast-math-flags to propagate here?
21234     SDValue Chain = Op.getOperand(0);
21235     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
21236                               {Chain, Or, Bias});
21237 
21238     if (Op.getValueType() == Sub.getValueType())
21239       return Sub;
21240 
21241     // Handle final rounding.
21242     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
21243         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
21244 
21245     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
21246   }
21247 
21248   // Subtract the bias.
21249   // TODO: Are there any fast-math-flags to propagate here?
21250   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
21251 
21252   // Handle final rounding.
21253   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
21254 }
21255 
21256 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
21257                                      const X86Subtarget &Subtarget,
21258                                      const SDLoc &DL) {
21259   if (Op.getSimpleValueType() != MVT::v2f64)
21260     return SDValue();
21261 
21262   bool IsStrict = Op->isStrictFPOpcode();
21263 
21264   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
21265   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
21266 
21267   if (Subtarget.hasAVX512()) {
21268     if (!Subtarget.hasVLX()) {
21269       // Let generic type legalization widen this.
21270       if (!IsStrict)
21271         return SDValue();
21272       // Otherwise pad the integer input with 0s and widen the operation.
21273       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
21274                        DAG.getConstant(0, DL, MVT::v2i32));
21275       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
21276                                 {Op.getOperand(0), N0});
21277       SDValue Chain = Res.getValue(1);
21278       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
21279                         DAG.getIntPtrConstant(0, DL));
21280       return DAG.getMergeValues({Res, Chain}, DL);
21281     }
21282 
21283     // Legalize to v4i32 type.
21284     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
21285                      DAG.getUNDEF(MVT::v2i32));
21286     if (IsStrict)
21287       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
21288                          {Op.getOperand(0), N0});
21289     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
21290   }
21291 
21292   // Zero extend to 2i64, OR with the floating point representation of 2^52.
21293   // This gives us the floating point equivalent of 2^52 + the i32 integer
21294   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
21295   // point leaving just our i32 integers in double format.
21296   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
21297   SDValue VBias =
21298       DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), DL, MVT::v2f64);
21299   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
21300                            DAG.getBitcast(MVT::v2i64, VBias));
21301   Or = DAG.getBitcast(MVT::v2f64, Or);
21302 
21303   if (IsStrict)
21304     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
21305                        {Op.getOperand(0), Or, VBias});
21306   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
21307 }
21308 
21309 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
21310                                      const X86Subtarget &Subtarget) {
21311   SDLoc DL(Op);
21312   bool IsStrict = Op->isStrictFPOpcode();
21313   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
21314   MVT VecIntVT = V.getSimpleValueType();
21315   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
21316          "Unsupported custom type");
21317 
21318   if (Subtarget.hasAVX512()) {
21319     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
21320     assert(!Subtarget.hasVLX() && "Unexpected features");
21321     MVT VT = Op->getSimpleValueType(0);
21322 
21323     // v8i32->v8f64 is legal with AVX512 so just return it.
21324     if (VT == MVT::v8f64)
21325       return Op;
21326 
21327     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
21328            "Unexpected VT!");
21329     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
21330     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
21331     // Need to concat with zero vector for strict fp to avoid spurious
21332     // exceptions.
21333     SDValue Tmp =
21334         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
21335     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
21336                     DAG.getIntPtrConstant(0, DL));
21337     SDValue Res, Chain;
21338     if (IsStrict) {
21339       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
21340                         {Op->getOperand(0), V});
21341       Chain = Res.getValue(1);
21342     } else {
21343       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
21344     }
21345 
21346     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
21347                       DAG.getIntPtrConstant(0, DL));
21348 
21349     if (IsStrict)
21350       return DAG.getMergeValues({Res, Chain}, DL);
21351     return Res;
21352   }
21353 
21354   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
21355       Op->getSimpleValueType(0) == MVT::v4f64) {
21356     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
21357     Constant *Bias = ConstantFP::get(
21358         *DAG.getContext(),
21359         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
21360     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
21361     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
21362     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
21363     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
21364     SDValue VBias = DAG.getMemIntrinsicNode(
21365         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
21366         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
21367         MachineMemOperand::MOLoad);
21368 
21369     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
21370                              DAG.getBitcast(MVT::v4i64, VBias));
21371     Or = DAG.getBitcast(MVT::v4f64, Or);
21372 
21373     if (IsStrict)
21374       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
21375                          {Op.getOperand(0), Or, VBias});
21376     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
21377   }
21378 
21379   // The algorithm is the following:
21380   // #ifdef __SSE4_1__
21381   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
21382   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
21383   //                                 (uint4) 0x53000000, 0xaa);
21384   // #else
21385   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
21386   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
21387   // #endif
21388   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
21389   //     return (float4) lo + fhi;
21390 
21391   bool Is128 = VecIntVT == MVT::v4i32;
21392   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
21393   // If we convert to something else than the supported type, e.g., to v4f64,
21394   // abort early.
21395   if (VecFloatVT != Op->getSimpleValueType(0))
21396     return SDValue();
21397 
21398   // In the #idef/#else code, we have in common:
21399   // - The vector of constants:
21400   // -- 0x4b000000
21401   // -- 0x53000000
21402   // - A shift:
21403   // -- v >> 16
21404 
21405   // Create the splat vector for 0x4b000000.
21406   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
21407   // Create the splat vector for 0x53000000.
21408   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
21409 
21410   // Create the right shift.
21411   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
21412   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
21413 
21414   SDValue Low, High;
21415   if (Subtarget.hasSSE41()) {
21416     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
21417     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
21418     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
21419     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
21420     // Low will be bitcasted right away, so do not bother bitcasting back to its
21421     // original type.
21422     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
21423                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
21424     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
21425     //                                 (uint4) 0x53000000, 0xaa);
21426     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
21427     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
21428     // High will be bitcasted right away, so do not bother bitcasting back to
21429     // its original type.
21430     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
21431                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
21432   } else {
21433     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
21434     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
21435     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
21436     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
21437 
21438     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
21439     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
21440   }
21441 
21442   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
21443   SDValue VecCstFSub = DAG.getConstantFP(
21444       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
21445 
21446   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
21447   // NOTE: By using fsub of a positive constant instead of fadd of a negative
21448   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
21449   // enabled. See PR24512.
21450   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
21451   // TODO: Are there any fast-math-flags to propagate here?
21452   //     (float4) lo;
21453   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
21454   //     return (float4) lo + fhi;
21455   if (IsStrict) {
21456     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
21457                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
21458     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
21459                        {FHigh.getValue(1), LowBitcast, FHigh});
21460   }
21461 
21462   SDValue FHigh =
21463       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
21464   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
21465 }
21466 
21467 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
21468                                    const X86Subtarget &Subtarget) {
21469   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
21470   SDValue N0 = Op.getOperand(OpNo);
21471   MVT SrcVT = N0.getSimpleValueType();
21472   SDLoc dl(Op);
21473 
21474   switch (SrcVT.SimpleTy) {
21475   default:
21476     llvm_unreachable("Custom UINT_TO_FP is not supported!");
21477   case MVT::v2i32:
21478     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
21479   case MVT::v4i32:
21480   case MVT::v8i32:
21481     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
21482   case MVT::v2i64:
21483   case MVT::v4i64:
21484     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
21485   }
21486 }
21487 
21488 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
21489                                            SelectionDAG &DAG) const {
21490   bool IsStrict = Op->isStrictFPOpcode();
21491   unsigned OpNo = IsStrict ? 1 : 0;
21492   SDValue Src = Op.getOperand(OpNo);
21493   SDLoc dl(Op);
21494   auto PtrVT = getPointerTy(DAG.getDataLayout());
21495   MVT SrcVT = Src.getSimpleValueType();
21496   MVT DstVT = Op->getSimpleValueType(0);
21497   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21498 
21499   // Bail out when we don't have native conversion instructions.
21500   if (DstVT == MVT::f128)
21501     return SDValue();
21502 
21503   if (isSoftFP16(DstVT))
21504     return promoteXINT_TO_FP(Op, DAG);
21505   else if (isLegalConversion(SrcVT, false, Subtarget))
21506     return Op;
21507 
21508   if (DstVT.isVector())
21509     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
21510 
21511   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
21512     return LowerWin64_INT128_TO_FP(Op, DAG);
21513 
21514   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
21515     return Extract;
21516 
21517   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
21518       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
21519     // Conversions from unsigned i32 to f32/f64 are legal,
21520     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
21521     return Op;
21522   }
21523 
21524   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
21525   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
21526     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
21527     if (IsStrict)
21528       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
21529                          {Chain, Src});
21530     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
21531   }
21532 
21533   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
21534     return V;
21535   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
21536     return V;
21537 
21538   // The transform for i64->f64 isn't correct for 0 when rounding to negative
21539   // infinity. It produces -0.0, so disable under strictfp.
21540   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && Subtarget.hasSSE2() &&
21541       !IsStrict)
21542     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
21543   // The transform for i32->f64/f32 isn't correct for 0 when rounding to
21544   // negative infinity. So disable under strictfp. Using FILD instead.
21545   if (SrcVT == MVT::i32 && Subtarget.hasSSE2() && DstVT != MVT::f80 &&
21546       !IsStrict)
21547     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
21548   if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
21549       (DstVT == MVT::f32 || DstVT == MVT::f64))
21550     return SDValue();
21551 
21552   // Make a 64-bit buffer, and use it to build an FILD.
21553   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
21554   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
21555   Align SlotAlign(8);
21556   MachinePointerInfo MPI =
21557     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
21558   if (SrcVT == MVT::i32) {
21559     SDValue OffsetSlot =
21560         DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
21561     SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
21562     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
21563                                   OffsetSlot, MPI.getWithOffset(4), SlotAlign);
21564     std::pair<SDValue, SDValue> Tmp =
21565         BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
21566     if (IsStrict)
21567       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
21568 
21569     return Tmp.first;
21570   }
21571 
21572   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
21573   SDValue ValueToStore = Src;
21574   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
21575     // Bitcasting to f64 here allows us to do a single 64-bit store from
21576     // an SSE register, avoiding the store forwarding penalty that would come
21577     // with two 32-bit stores.
21578     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
21579   }
21580   SDValue Store =
21581       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
21582   // For i64 source, we need to add the appropriate power of 2 if the input
21583   // was negative. We must be careful to do the computation in x87 extended
21584   // precision, not in SSE.
21585   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21586   SDValue Ops[] = { Store, StackSlot };
21587   SDValue Fild =
21588       DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
21589                               SlotAlign, MachineMemOperand::MOLoad);
21590   Chain = Fild.getValue(1);
21591 
21592 
21593   // Check whether the sign bit is set.
21594   SDValue SignSet = DAG.getSetCC(
21595       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
21596       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
21597 
21598   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
21599   APInt FF(64, 0x5F80000000000000ULL);
21600   SDValue FudgePtr = DAG.getConstantPool(
21601       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
21602   Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
21603 
21604   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
21605   SDValue Zero = DAG.getIntPtrConstant(0, dl);
21606   SDValue Four = DAG.getIntPtrConstant(4, dl);
21607   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
21608   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
21609 
21610   // Load the value out, extending it from f32 to f80.
21611   SDValue Fudge = DAG.getExtLoad(
21612       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
21613       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
21614       CPAlignment);
21615   Chain = Fudge.getValue(1);
21616   // Extend everything to 80 bits to force it to be done on x87.
21617   // TODO: Are there any fast-math-flags to propagate here?
21618   if (IsStrict) {
21619     SDValue Add = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::f80, MVT::Other},
21620                               {Chain, Fild, Fudge});
21621     // STRICT_FP_ROUND can't handle equal types.
21622     if (DstVT == MVT::f80)
21623       return Add;
21624     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
21625                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
21626   }
21627   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
21628   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
21629                      DAG.getIntPtrConstant(0, dl));
21630 }
21631 
21632 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
21633 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
21634 // just return an SDValue().
21635 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
21636 // to i16, i32 or i64, and we lower it to a legal sequence and return the
21637 // result.
21638 SDValue
21639 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
21640                                    bool IsSigned, SDValue &Chain) const {
21641   bool IsStrict = Op->isStrictFPOpcode();
21642   SDLoc DL(Op);
21643 
21644   EVT DstTy = Op.getValueType();
21645   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
21646   EVT TheVT = Value.getValueType();
21647   auto PtrVT = getPointerTy(DAG.getDataLayout());
21648 
21649   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
21650     // f16 must be promoted before using the lowering in this routine.
21651     // fp128 does not use this lowering.
21652     return SDValue();
21653   }
21654 
21655   // If using FIST to compute an unsigned i64, we'll need some fixup
21656   // to handle values above the maximum signed i64.  A FIST is always
21657   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
21658   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
21659 
21660   // FIXME: This does not generate an invalid exception if the input does not
21661   // fit in i32. PR44019
21662   if (!IsSigned && DstTy != MVT::i64) {
21663     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
21664     // The low 32 bits of the fist result will have the correct uint32 result.
21665     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
21666     DstTy = MVT::i64;
21667   }
21668 
21669   assert(DstTy.getSimpleVT() <= MVT::i64 &&
21670          DstTy.getSimpleVT() >= MVT::i16 &&
21671          "Unknown FP_TO_INT to lower!");
21672 
21673   // We lower FP->int64 into FISTP64 followed by a load from a temporary
21674   // stack slot.
21675   MachineFunction &MF = DAG.getMachineFunction();
21676   unsigned MemSize = DstTy.getStoreSize();
21677   int SSFI =
21678       MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
21679   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
21680 
21681   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21682 
21683   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
21684 
21685   if (UnsignedFixup) {
21686     //
21687     // Conversion to unsigned i64 is implemented with a select,
21688     // depending on whether the source value fits in the range
21689     // of a signed i64.  Let Thresh be the FP equivalent of
21690     // 0x8000000000000000ULL.
21691     //
21692     //  Adjust = (Value >= Thresh) ? 0x80000000 : 0;
21693     //  FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
21694     //  FistSrc = (Value - FltOfs);
21695     //  Fist-to-mem64 FistSrc
21696     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
21697     //  to XOR'ing the high 32 bits with Adjust.
21698     //
21699     // Being a power of 2, Thresh is exactly representable in all FP formats.
21700     // For X87 we'd like to use the smallest FP type for this constant, but
21701     // for DAG type consistency we have to match the FP operand type.
21702 
21703     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
21704     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
21705     bool LosesInfo = false;
21706     if (TheVT == MVT::f64)
21707       // The rounding mode is irrelevant as the conversion should be exact.
21708       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
21709                               &LosesInfo);
21710     else if (TheVT == MVT::f80)
21711       Status = Thresh.convert(APFloat::x87DoubleExtended(),
21712                               APFloat::rmNearestTiesToEven, &LosesInfo);
21713 
21714     assert(Status == APFloat::opOK && !LosesInfo &&
21715            "FP conversion should have been exact");
21716 
21717     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
21718 
21719     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
21720                                    *DAG.getContext(), TheVT);
21721     SDValue Cmp;
21722     if (IsStrict) {
21723       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
21724                          /*IsSignaling*/ true);
21725       Chain = Cmp.getValue(1);
21726     } else {
21727       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
21728     }
21729 
21730     // Our preferred lowering of
21731     //
21732     // (Value >= Thresh) ? 0x8000000000000000ULL : 0
21733     //
21734     // is
21735     //
21736     // (Value >= Thresh) << 63
21737     //
21738     // but since we can get here after LegalOperations, DAGCombine might do the
21739     // wrong thing if we create a select. So, directly create the preferred
21740     // version.
21741     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
21742     SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
21743     Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
21744 
21745     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
21746                                    DAG.getConstantFP(0.0, DL, TheVT));
21747 
21748     if (IsStrict) {
21749       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
21750                           { Chain, Value, FltOfs });
21751       Chain = Value.getValue(1);
21752     } else
21753       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
21754   }
21755 
21756   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
21757 
21758   // FIXME This causes a redundant load/store if the SSE-class value is already
21759   // in memory, such as if it is on the callstack.
21760   if (isScalarFPTypeInSSEReg(TheVT)) {
21761     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
21762     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
21763     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21764     SDValue Ops[] = { Chain, StackSlot };
21765 
21766     unsigned FLDSize = TheVT.getStoreSize();
21767     assert(FLDSize <= MemSize && "Stack slot not big enough");
21768     MachineMemOperand *MMO = MF.getMachineMemOperand(
21769         MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
21770     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
21771     Chain = Value.getValue(1);
21772   }
21773 
21774   // Build the FP_TO_INT*_IN_MEM
21775   MachineMemOperand *MMO = MF.getMachineMemOperand(
21776       MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
21777   SDValue Ops[] = { Chain, Value, StackSlot };
21778   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
21779                                          DAG.getVTList(MVT::Other),
21780                                          Ops, DstTy, MMO);
21781 
21782   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
21783   Chain = Res.getValue(1);
21784 
21785   // If we need an unsigned fixup, XOR the result with adjust.
21786   if (UnsignedFixup)
21787     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
21788 
21789   return Res;
21790 }
21791 
21792 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
21793                               const X86Subtarget &Subtarget) {
21794   MVT VT = Op.getSimpleValueType();
21795   SDValue In = Op.getOperand(0);
21796   MVT InVT = In.getSimpleValueType();
21797   SDLoc dl(Op);
21798   unsigned Opc = Op.getOpcode();
21799 
21800   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
21801   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
21802          "Unexpected extension opcode");
21803   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
21804          "Expected same number of elements");
21805   assert((VT.getVectorElementType() == MVT::i16 ||
21806           VT.getVectorElementType() == MVT::i32 ||
21807           VT.getVectorElementType() == MVT::i64) &&
21808          "Unexpected element type");
21809   assert((InVT.getVectorElementType() == MVT::i8 ||
21810           InVT.getVectorElementType() == MVT::i16 ||
21811           InVT.getVectorElementType() == MVT::i32) &&
21812          "Unexpected element type");
21813 
21814   unsigned ExtendInVecOpc = getOpcode_EXTEND_VECTOR_INREG(Opc);
21815 
21816   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
21817     assert(InVT == MVT::v32i8 && "Unexpected VT!");
21818     return splitVectorIntUnary(Op, DAG);
21819   }
21820 
21821   if (Subtarget.hasInt256())
21822     return Op;
21823 
21824   // Optimize vectors in AVX mode:
21825   //
21826   //   v8i16 -> v8i32
21827   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
21828   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
21829   //   Concat upper and lower parts.
21830   //
21831   //   v4i32 -> v4i64
21832   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
21833   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
21834   //   Concat upper and lower parts.
21835   //
21836   MVT HalfVT = VT.getHalfNumVectorElementsVT();
21837   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
21838 
21839   // Short-circuit if we can determine that each 128-bit half is the same value.
21840   // Otherwise, this is difficult to match and optimize.
21841   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
21842     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
21843       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
21844 
21845   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
21846   SDValue Undef = DAG.getUNDEF(InVT);
21847   bool NeedZero = Opc == ISD::ZERO_EXTEND;
21848   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
21849   OpHi = DAG.getBitcast(HalfVT, OpHi);
21850 
21851   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
21852 }
21853 
21854 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
21855 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
21856                                    const SDLoc &dl, SelectionDAG &DAG) {
21857   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
21858   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
21859                            DAG.getIntPtrConstant(0, dl));
21860   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
21861                            DAG.getIntPtrConstant(8, dl));
21862   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
21863   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
21864   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
21865   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21866 }
21867 
21868 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
21869                                       const X86Subtarget &Subtarget,
21870                                       SelectionDAG &DAG) {
21871   MVT VT = Op->getSimpleValueType(0);
21872   SDValue In = Op->getOperand(0);
21873   MVT InVT = In.getSimpleValueType();
21874   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
21875   SDLoc DL(Op);
21876   unsigned NumElts = VT.getVectorNumElements();
21877 
21878   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
21879   // avoids a constant pool load.
21880   if (VT.getVectorElementType() != MVT::i8) {
21881     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
21882     return DAG.getNode(ISD::SRL, DL, VT, Extend,
21883                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
21884   }
21885 
21886   // Extend VT if BWI is not supported.
21887   MVT ExtVT = VT;
21888   if (!Subtarget.hasBWI()) {
21889     // If v16i32 is to be avoided, we'll need to split and concatenate.
21890     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
21891       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
21892 
21893     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
21894   }
21895 
21896   // Widen to 512-bits if VLX is not supported.
21897   MVT WideVT = ExtVT;
21898   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
21899     NumElts *= 512 / ExtVT.getSizeInBits();
21900     InVT = MVT::getVectorVT(MVT::i1, NumElts);
21901     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
21902                      In, DAG.getIntPtrConstant(0, DL));
21903     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
21904                               NumElts);
21905   }
21906 
21907   SDValue One = DAG.getConstant(1, DL, WideVT);
21908   SDValue Zero = DAG.getConstant(0, DL, WideVT);
21909 
21910   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
21911 
21912   // Truncate if we had to extend above.
21913   if (VT != ExtVT) {
21914     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
21915     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
21916   }
21917 
21918   // Extract back to 128/256-bit if we widened.
21919   if (WideVT != VT)
21920     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
21921                               DAG.getIntPtrConstant(0, DL));
21922 
21923   return SelectedVal;
21924 }
21925 
21926 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
21927                                 SelectionDAG &DAG) {
21928   SDValue In = Op.getOperand(0);
21929   MVT SVT = In.getSimpleValueType();
21930 
21931   if (SVT.getVectorElementType() == MVT::i1)
21932     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
21933 
21934   assert(Subtarget.hasAVX() && "Expected AVX support");
21935   return LowerAVXExtend(Op, DAG, Subtarget);
21936 }
21937 
21938 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
21939 /// It makes use of the fact that vectors with enough leading sign/zero bits
21940 /// prevent the PACKSS/PACKUS from saturating the results.
21941 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
21942 /// within each 128-bit lane.
21943 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
21944                                       const SDLoc &DL, SelectionDAG &DAG,
21945                                       const X86Subtarget &Subtarget) {
21946   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
21947          "Unexpected PACK opcode");
21948   assert(DstVT.isVector() && "VT not a vector?");
21949 
21950   // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
21951   if (!Subtarget.hasSSE2())
21952     return SDValue();
21953 
21954   EVT SrcVT = In.getValueType();
21955 
21956   // No truncation required, we might get here due to recursive calls.
21957   if (SrcVT == DstVT)
21958     return In;
21959 
21960   // We only support vector truncation to 64bits or greater from a
21961   // 128bits or greater source.
21962   unsigned DstSizeInBits = DstVT.getSizeInBits();
21963   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
21964   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
21965     return SDValue();
21966 
21967   unsigned NumElems = SrcVT.getVectorNumElements();
21968   if (!isPowerOf2_32(NumElems))
21969     return SDValue();
21970 
21971   LLVMContext &Ctx = *DAG.getContext();
21972   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
21973   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
21974 
21975   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
21976 
21977   // Pack to the largest type possible:
21978   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
21979   EVT InVT = MVT::i16, OutVT = MVT::i8;
21980   if (SrcVT.getScalarSizeInBits() > 16 &&
21981       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
21982     InVT = MVT::i32;
21983     OutVT = MVT::i16;
21984   }
21985 
21986   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
21987   if (SrcVT.is128BitVector()) {
21988     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
21989     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
21990     In = DAG.getBitcast(InVT, In);
21991     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, DAG.getUNDEF(InVT));
21992     Res = extractSubVector(Res, 0, DAG, DL, 64);
21993     return DAG.getBitcast(DstVT, Res);
21994   }
21995 
21996   // Split lower/upper subvectors.
21997   SDValue Lo, Hi;
21998   std::tie(Lo, Hi) = splitVector(In, DAG, DL);
21999 
22000   unsigned SubSizeInBits = SrcSizeInBits / 2;
22001   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
22002   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
22003 
22004   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
22005   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
22006     Lo = DAG.getBitcast(InVT, Lo);
22007     Hi = DAG.getBitcast(InVT, Hi);
22008     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
22009     return DAG.getBitcast(DstVT, Res);
22010   }
22011 
22012   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
22013   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
22014   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
22015     Lo = DAG.getBitcast(InVT, Lo);
22016     Hi = DAG.getBitcast(InVT, Hi);
22017     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
22018 
22019     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
22020     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
22021     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
22022     SmallVector<int, 64> Mask;
22023     int Scale = 64 / OutVT.getScalarSizeInBits();
22024     narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
22025     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
22026 
22027     if (DstVT.is256BitVector())
22028       return DAG.getBitcast(DstVT, Res);
22029 
22030     // If 512bit -> 128bit truncate another stage.
22031     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
22032     Res = DAG.getBitcast(PackedVT, Res);
22033     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
22034   }
22035 
22036   // Recursively pack lower/upper subvectors, concat result and pack again.
22037   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
22038   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
22039   Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
22040   Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
22041 
22042   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
22043   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
22044   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
22045 }
22046 
22047 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
22048                                   const X86Subtarget &Subtarget) {
22049 
22050   SDLoc DL(Op);
22051   MVT VT = Op.getSimpleValueType();
22052   SDValue In = Op.getOperand(0);
22053   MVT InVT = In.getSimpleValueType();
22054 
22055   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
22056 
22057   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
22058   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
22059   if (InVT.getScalarSizeInBits() <= 16) {
22060     if (Subtarget.hasBWI()) {
22061       // legal, will go to VPMOVB2M, VPMOVW2M
22062       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
22063         // We need to shift to get the lsb into sign position.
22064         // Shift packed bytes not supported natively, bitcast to word
22065         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
22066         In = DAG.getNode(ISD::SHL, DL, ExtVT,
22067                          DAG.getBitcast(ExtVT, In),
22068                          DAG.getConstant(ShiftInx, DL, ExtVT));
22069         In = DAG.getBitcast(InVT, In);
22070       }
22071       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
22072                           In, ISD::SETGT);
22073     }
22074     // Use TESTD/Q, extended vector to packed dword/qword.
22075     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
22076            "Unexpected vector type.");
22077     unsigned NumElts = InVT.getVectorNumElements();
22078     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
22079     // We need to change to a wider element type that we have support for.
22080     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
22081     // For 16 element vectors we extend to v16i32 unless we are explicitly
22082     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
22083     // we need to split into two 8 element vectors which we can extend to v8i32,
22084     // truncate and concat the results. There's an additional complication if
22085     // the original type is v16i8. In that case we can't split the v16i8
22086     // directly, so we need to shuffle high elements to low and use
22087     // sign_extend_vector_inreg.
22088     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
22089       SDValue Lo, Hi;
22090       if (InVT == MVT::v16i8) {
22091         Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
22092         Hi = DAG.getVectorShuffle(
22093             InVT, DL, In, In,
22094             {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
22095         Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
22096       } else {
22097         assert(InVT == MVT::v16i16 && "Unexpected VT!");
22098         Lo = extract128BitVector(In, 0, DAG, DL);
22099         Hi = extract128BitVector(In, 8, DAG, DL);
22100       }
22101       // We're split now, just emit two truncates and a concat. The two
22102       // truncates will trigger legalization to come back to this function.
22103       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
22104       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
22105       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
22106     }
22107     // We either have 8 elements or we're allowed to use 512-bit vectors.
22108     // If we have VLX, we want to use the narrowest vector that can get the
22109     // job done so we use vXi32.
22110     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
22111     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
22112     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
22113     InVT = ExtVT;
22114     ShiftInx = InVT.getScalarSizeInBits() - 1;
22115   }
22116 
22117   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
22118     // We need to shift to get the lsb into sign position.
22119     In = DAG.getNode(ISD::SHL, DL, InVT, In,
22120                      DAG.getConstant(ShiftInx, DL, InVT));
22121   }
22122   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
22123   if (Subtarget.hasDQI())
22124     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
22125   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
22126 }
22127 
22128 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
22129   SDLoc DL(Op);
22130   MVT VT = Op.getSimpleValueType();
22131   SDValue In = Op.getOperand(0);
22132   MVT InVT = In.getSimpleValueType();
22133   unsigned InNumEltBits = InVT.getScalarSizeInBits();
22134 
22135   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
22136          "Invalid TRUNCATE operation");
22137 
22138   // If we're called by the type legalizer, handle a few cases.
22139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22140   if (!TLI.isTypeLegal(InVT)) {
22141     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
22142         VT.is128BitVector()) {
22143       assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
22144              "Unexpected subtarget!");
22145       // The default behavior is to truncate one step, concatenate, and then
22146       // truncate the remainder. We'd rather produce two 64-bit results and
22147       // concatenate those.
22148       SDValue Lo, Hi;
22149       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
22150 
22151       EVT LoVT, HiVT;
22152       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
22153 
22154       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
22155       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
22156       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
22157     }
22158 
22159     // Otherwise let default legalization handle it.
22160     return SDValue();
22161   }
22162 
22163   if (VT.getVectorElementType() == MVT::i1)
22164     return LowerTruncateVecI1(Op, DAG, Subtarget);
22165 
22166   // vpmovqb/w/d, vpmovdb/w, vpmovwb
22167   if (Subtarget.hasAVX512()) {
22168     if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
22169       assert(VT == MVT::v32i8 && "Unexpected VT!");
22170       return splitVectorIntUnary(Op, DAG);
22171     }
22172 
22173     // word to byte only under BWI. Otherwise we have to promoted to v16i32
22174     // and then truncate that. But we should only do that if we haven't been
22175     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
22176     // handled by isel patterns.
22177     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
22178         Subtarget.canExtendTo512DQ())
22179       return Op;
22180   }
22181 
22182   unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
22183   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
22184 
22185   // Truncate with PACKUS if we are truncating a vector with leading zero bits
22186   // that extend all the way to the packed/truncated value.
22187   // Pre-SSE41 we can only use PACKUSWB.
22188   KnownBits Known = DAG.computeKnownBits(In);
22189   if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
22190     if (SDValue V =
22191             truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
22192       return V;
22193 
22194   // Truncate with PACKSS if we are truncating a vector with sign-bits that
22195   // extend all the way to the packed/truncated value.
22196   if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
22197     if (SDValue V =
22198             truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
22199       return V;
22200 
22201   // Handle truncation of V256 to V128 using shuffles.
22202   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
22203 
22204   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
22205     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
22206     if (Subtarget.hasInt256()) {
22207       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
22208       In = DAG.getBitcast(MVT::v8i32, In);
22209       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
22210       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
22211                          DAG.getIntPtrConstant(0, DL));
22212     }
22213 
22214     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
22215                                DAG.getIntPtrConstant(0, DL));
22216     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
22217                                DAG.getIntPtrConstant(2, DL));
22218     static const int ShufMask[] = {0, 2, 4, 6};
22219     return DAG.getVectorShuffle(VT, DL, DAG.getBitcast(MVT::v4i32, OpLo),
22220                                 DAG.getBitcast(MVT::v4i32, OpHi), ShufMask);
22221   }
22222 
22223   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
22224     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
22225     if (Subtarget.hasInt256()) {
22226       // The PSHUFB mask:
22227       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
22228                                       -1, -1, -1, -1, -1, -1, -1, -1,
22229                                       16, 17, 20, 21, 24, 25, 28, 29,
22230                                       -1, -1, -1, -1, -1, -1, -1, -1 };
22231       In = DAG.getBitcast(MVT::v32i8, In);
22232       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
22233       In = DAG.getBitcast(MVT::v4i64, In);
22234 
22235       static const int ShufMask2[] = {0, 2, -1, -1};
22236       In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
22237       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
22238                        DAG.getIntPtrConstant(0, DL));
22239       return DAG.getBitcast(MVT::v8i16, In);
22240     }
22241 
22242     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
22243                                DAG.getIntPtrConstant(0, DL));
22244     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
22245                                DAG.getIntPtrConstant(4, DL));
22246 
22247     // The PSHUFB mask:
22248     static const int ShufMask1[] = {0, 2, 4, 6, -1, -1, -1, -1};
22249 
22250     OpLo = DAG.getBitcast(MVT::v8i16, OpLo);
22251     OpHi = DAG.getBitcast(MVT::v8i16, OpHi);
22252 
22253     OpLo = DAG.getVectorShuffle(MVT::v8i16, DL, OpLo, OpLo, ShufMask1);
22254     OpHi = DAG.getVectorShuffle(MVT::v8i16, DL, OpHi, OpHi, ShufMask1);
22255 
22256     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
22257     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
22258 
22259     // The MOVLHPS Mask:
22260     static const int ShufMask2[] = {0, 1, 4, 5};
22261     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
22262     return DAG.getBitcast(MVT::v8i16, res);
22263   }
22264 
22265   if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
22266     // Use an AND to zero uppper bits for PACKUS.
22267     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
22268 
22269     SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
22270                                DAG.getIntPtrConstant(0, DL));
22271     SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
22272                                DAG.getIntPtrConstant(8, DL));
22273     return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
22274   }
22275 
22276   llvm_unreachable("All 256->128 cases should have been handled above!");
22277 }
22278 
22279 // We can leverage the specific way the "cvttps2dq/cvttpd2dq" instruction
22280 // behaves on out of range inputs to generate optimized conversions.
22281 static SDValue expandFP_TO_UINT_SSE(MVT VT, SDValue Src, const SDLoc &dl,
22282                                     SelectionDAG &DAG,
22283                                     const X86Subtarget &Subtarget) {
22284   MVT SrcVT = Src.getSimpleValueType();
22285   unsigned DstBits = VT.getScalarSizeInBits();
22286   assert(DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported");
22287 
22288   // Calculate the converted result for values in the range 0 to
22289   // 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
22290   SDValue Small = DAG.getNode(X86ISD::CVTTP2SI, dl, VT, Src);
22291   SDValue Big =
22292       DAG.getNode(X86ISD::CVTTP2SI, dl, VT,
22293                   DAG.getNode(ISD::FSUB, dl, SrcVT, Src,
22294                               DAG.getConstantFP(2147483648.0f, dl, SrcVT)));
22295 
22296   // The "CVTTP2SI" instruction conveniently sets the sign bit if
22297   // and only if the value was out of range. So we can use that
22298   // as our indicator that we rather use "Big" instead of "Small".
22299   //
22300   // Use "Small" if "IsOverflown" has all bits cleared
22301   // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
22302 
22303   // AVX1 can't use the signsplat masking for 256-bit vectors - we have to
22304   // use the slightly slower blendv select instead.
22305   if (VT == MVT::v8i32 && !Subtarget.hasAVX2()) {
22306     SDValue Overflow = DAG.getNode(ISD::OR, dl, VT, Small, Big);
22307     return DAG.getNode(X86ISD::BLENDV, dl, VT, Small, Overflow, Small);
22308   }
22309 
22310   SDValue IsOverflown =
22311       DAG.getNode(X86ISD::VSRAI, dl, VT, Small,
22312                   DAG.getTargetConstant(DstBits - 1, dl, MVT::i8));
22313   return DAG.getNode(ISD::OR, dl, VT, Small,
22314                      DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
22315 }
22316 
22317 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
22318   bool IsStrict = Op->isStrictFPOpcode();
22319   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
22320                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
22321   MVT VT = Op->getSimpleValueType(0);
22322   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
22323   SDValue Chain = IsStrict ? Op->getOperand(0) : SDValue();
22324   MVT SrcVT = Src.getSimpleValueType();
22325   SDLoc dl(Op);
22326 
22327   SDValue Res;
22328   if (isSoftFP16(SrcVT)) {
22329     MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
22330     if (IsStrict)
22331       return DAG.getNode(Op.getOpcode(), dl, {VT, MVT::Other},
22332                          {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
22333                                              {NVT, MVT::Other}, {Chain, Src})});
22334     return DAG.getNode(Op.getOpcode(), dl, VT,
22335                        DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
22336   } else if (isTypeLegal(SrcVT) && isLegalConversion(VT, IsSigned, Subtarget)) {
22337     return Op;
22338   }
22339 
22340   if (VT.isVector()) {
22341     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
22342       MVT ResVT = MVT::v4i32;
22343       MVT TruncVT = MVT::v4i1;
22344       unsigned Opc;
22345       if (IsStrict)
22346         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
22347       else
22348         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
22349 
22350       if (!IsSigned && !Subtarget.hasVLX()) {
22351         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
22352         // Widen to 512-bits.
22353         ResVT = MVT::v8i32;
22354         TruncVT = MVT::v8i1;
22355         Opc = Op.getOpcode();
22356         // Need to concat with zero vector for strict fp to avoid spurious
22357         // exceptions.
22358         // TODO: Should we just do this for non-strict as well?
22359         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
22360                                : DAG.getUNDEF(MVT::v8f64);
22361         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
22362                           DAG.getIntPtrConstant(0, dl));
22363       }
22364       if (IsStrict) {
22365         Res = DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Chain, Src});
22366         Chain = Res.getValue(1);
22367       } else {
22368         Res = DAG.getNode(Opc, dl, ResVT, Src);
22369       }
22370 
22371       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
22372       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
22373                         DAG.getIntPtrConstant(0, dl));
22374       if (IsStrict)
22375         return DAG.getMergeValues({Res, Chain}, dl);
22376       return Res;
22377     }
22378 
22379     if (Subtarget.hasFP16() && SrcVT.getVectorElementType() == MVT::f16) {
22380       if (VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16)
22381         return Op;
22382 
22383       MVT ResVT = VT;
22384       MVT EleVT = VT.getVectorElementType();
22385       if (EleVT != MVT::i64)
22386         ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
22387 
22388       if (SrcVT != MVT::v8f16) {
22389         SDValue Tmp =
22390             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
22391         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
22392         Ops[0] = Src;
22393         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
22394       }
22395 
22396       if (IsStrict) {
22397         Res = DAG.getNode(IsSigned ? X86ISD::STRICT_CVTTP2SI
22398                                    : X86ISD::STRICT_CVTTP2UI,
22399                           dl, {ResVT, MVT::Other}, {Chain, Src});
22400         Chain = Res.getValue(1);
22401       } else {
22402         Res = DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl,
22403                           ResVT, Src);
22404       }
22405 
22406       // TODO: Need to add exception check code for strict FP.
22407       if (EleVT.getSizeInBits() < 16) {
22408         ResVT = MVT::getVectorVT(EleVT, 8);
22409         Res = DAG.getNode(ISD::TRUNCATE, dl, ResVT, Res);
22410       }
22411 
22412       if (ResVT != VT)
22413         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
22414                           DAG.getIntPtrConstant(0, dl));
22415 
22416       if (IsStrict)
22417         return DAG.getMergeValues({Res, Chain}, dl);
22418       return Res;
22419     }
22420 
22421     if (VT == MVT::v8i16 && (SrcVT == MVT::v8f32 || SrcVT == MVT::v8f64)) {
22422       if (IsStrict) {
22423         Res = DAG.getNode(IsSigned ? ISD::STRICT_FP_TO_SINT
22424                                    : ISD::STRICT_FP_TO_UINT,
22425                           dl, {MVT::v8i32, MVT::Other}, {Chain, Src});
22426         Chain = Res.getValue(1);
22427       } else {
22428         Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl,
22429                           MVT::v8i32, Src);
22430       }
22431 
22432       // TODO: Need to add exception check code for strict FP.
22433       Res = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i16, Res);
22434 
22435       if (IsStrict)
22436         return DAG.getMergeValues({Res, Chain}, dl);
22437       return Res;
22438     }
22439 
22440     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
22441     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
22442       assert(!IsSigned && "Expected unsigned conversion!");
22443       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
22444       return Op;
22445     }
22446 
22447     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
22448     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
22449         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32) &&
22450         Subtarget.useAVX512Regs()) {
22451       assert(!IsSigned && "Expected unsigned conversion!");
22452       assert(!Subtarget.hasVLX() && "Unexpected features!");
22453       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
22454       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
22455       // Need to concat with zero vector for strict fp to avoid spurious
22456       // exceptions.
22457       // TODO: Should we just do this for non-strict as well?
22458       SDValue Tmp =
22459           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
22460       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
22461                         DAG.getIntPtrConstant(0, dl));
22462 
22463       if (IsStrict) {
22464         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
22465                           {Chain, Src});
22466         Chain = Res.getValue(1);
22467       } else {
22468         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
22469       }
22470 
22471       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
22472                         DAG.getIntPtrConstant(0, dl));
22473 
22474       if (IsStrict)
22475         return DAG.getMergeValues({Res, Chain}, dl);
22476       return Res;
22477     }
22478 
22479     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
22480     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
22481         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32) &&
22482         Subtarget.useAVX512Regs() && Subtarget.hasDQI()) {
22483       assert(!Subtarget.hasVLX() && "Unexpected features!");
22484       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
22485       // Need to concat with zero vector for strict fp to avoid spurious
22486       // exceptions.
22487       // TODO: Should we just do this for non-strict as well?
22488       SDValue Tmp =
22489           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
22490       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
22491                         DAG.getIntPtrConstant(0, dl));
22492 
22493       if (IsStrict) {
22494         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
22495                           {Chain, Src});
22496         Chain = Res.getValue(1);
22497       } else {
22498         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
22499       }
22500 
22501       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
22502                         DAG.getIntPtrConstant(0, dl));
22503 
22504       if (IsStrict)
22505         return DAG.getMergeValues({Res, Chain}, dl);
22506       return Res;
22507     }
22508 
22509     if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
22510       if (!Subtarget.hasVLX()) {
22511         // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
22512         // legalizer and then widened again by vector op legalization.
22513         if (!IsStrict)
22514           return SDValue();
22515 
22516         SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
22517         SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
22518                                   {Src, Zero, Zero, Zero});
22519         Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
22520                           {Chain, Tmp});
22521         SDValue Chain = Tmp.getValue(1);
22522         Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
22523                           DAG.getIntPtrConstant(0, dl));
22524         return DAG.getMergeValues({Tmp, Chain}, dl);
22525       }
22526 
22527       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
22528       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
22529                                 DAG.getUNDEF(MVT::v2f32));
22530       if (IsStrict) {
22531         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
22532                                 : X86ISD::STRICT_CVTTP2UI;
22533         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
22534       }
22535       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
22536       return DAG.getNode(Opc, dl, VT, Tmp);
22537     }
22538 
22539     // Generate optimized instructions for pre AVX512 unsigned conversions from
22540     // vXf32 to vXi32.
22541     if ((VT == MVT::v4i32 && SrcVT == MVT::v4f32) ||
22542         (VT == MVT::v4i32 && SrcVT == MVT::v4f64) ||
22543         (VT == MVT::v8i32 && SrcVT == MVT::v8f32)) {
22544       assert(!IsSigned && "Expected unsigned conversion!");
22545       return expandFP_TO_UINT_SSE(VT, Src, dl, DAG, Subtarget);
22546     }
22547 
22548     return SDValue();
22549   }
22550 
22551   assert(!VT.isVector());
22552 
22553   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
22554 
22555   if (!IsSigned && UseSSEReg) {
22556     // Conversions from f32/f64 with AVX512 should be legal.
22557     if (Subtarget.hasAVX512())
22558       return Op;
22559 
22560     // We can leverage the specific way the "cvttss2si/cvttsd2si" instruction
22561     // behaves on out of range inputs to generate optimized conversions.
22562     if (!IsStrict && ((VT == MVT::i32 && !Subtarget.is64Bit()) ||
22563                       (VT == MVT::i64 && Subtarget.is64Bit()))) {
22564       unsigned DstBits = VT.getScalarSizeInBits();
22565       APInt UIntLimit = APInt::getSignMask(DstBits);
22566       SDValue FloatOffset = DAG.getNode(ISD::UINT_TO_FP, dl, SrcVT,
22567                                         DAG.getConstant(UIntLimit, dl, VT));
22568       MVT SrcVecVT = MVT::getVectorVT(SrcVT, 128 / SrcVT.getScalarSizeInBits());
22569 
22570       // Calculate the converted result for values in the range:
22571       // (i32) 0 to 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
22572       // (i64) 0 to 2^63-1 ("Small") and from 2^63 to 2^64-1 ("Big").
22573       SDValue Small =
22574           DAG.getNode(X86ISD::CVTTS2SI, dl, VT,
22575                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT, Src));
22576       SDValue Big = DAG.getNode(
22577           X86ISD::CVTTS2SI, dl, VT,
22578           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT,
22579                       DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FloatOffset)));
22580 
22581       // The "CVTTS2SI" instruction conveniently sets the sign bit if
22582       // and only if the value was out of range. So we can use that
22583       // as our indicator that we rather use "Big" instead of "Small".
22584       //
22585       // Use "Small" if "IsOverflown" has all bits cleared
22586       // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
22587       SDValue IsOverflown = DAG.getNode(
22588           ISD::SRA, dl, VT, Small, DAG.getConstant(DstBits - 1, dl, MVT::i8));
22589       return DAG.getNode(ISD::OR, dl, VT, Small,
22590                          DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
22591     }
22592 
22593     // Use default expansion for i64.
22594     if (VT == MVT::i64)
22595       return SDValue();
22596 
22597     assert(VT == MVT::i32 && "Unexpected VT!");
22598 
22599     // Promote i32 to i64 and use a signed operation on 64-bit targets.
22600     // FIXME: This does not generate an invalid exception if the input does not
22601     // fit in i32. PR44019
22602     if (Subtarget.is64Bit()) {
22603       if (IsStrict) {
22604         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i64, MVT::Other},
22605                           {Chain, Src});
22606         Chain = Res.getValue(1);
22607       } else
22608         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
22609 
22610       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
22611       if (IsStrict)
22612         return DAG.getMergeValues({Res, Chain}, dl);
22613       return Res;
22614     }
22615 
22616     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
22617     // use fisttp which will be handled later.
22618     if (!Subtarget.hasSSE3())
22619       return SDValue();
22620   }
22621 
22622   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
22623   // FIXME: This does not generate an invalid exception if the input does not
22624   // fit in i16. PR44019
22625   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
22626     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
22627     if (IsStrict) {
22628       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i32, MVT::Other},
22629                         {Chain, Src});
22630       Chain = Res.getValue(1);
22631     } else
22632       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
22633 
22634     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
22635     if (IsStrict)
22636       return DAG.getMergeValues({Res, Chain}, dl);
22637     return Res;
22638   }
22639 
22640   // If this is a FP_TO_SINT using SSEReg we're done.
22641   if (UseSSEReg && IsSigned)
22642     return Op;
22643 
22644   // fp128 needs to use a libcall.
22645   if (SrcVT == MVT::f128) {
22646     RTLIB::Libcall LC;
22647     if (IsSigned)
22648       LC = RTLIB::getFPTOSINT(SrcVT, VT);
22649     else
22650       LC = RTLIB::getFPTOUINT(SrcVT, VT);
22651 
22652     MakeLibCallOptions CallOptions;
22653     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
22654                                                   SDLoc(Op), Chain);
22655 
22656     if (IsStrict)
22657       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
22658 
22659     return Tmp.first;
22660   }
22661 
22662   // Fall back to X87.
22663   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
22664     if (IsStrict)
22665       return DAG.getMergeValues({V, Chain}, dl);
22666     return V;
22667   }
22668 
22669   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
22670 }
22671 
22672 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
22673                                              SelectionDAG &DAG) const {
22674   SDValue Src = Op.getOperand(0);
22675   MVT SrcVT = Src.getSimpleValueType();
22676 
22677   if (SrcVT == MVT::f16)
22678     return SDValue();
22679 
22680   // If the source is in an SSE register, the node is Legal.
22681   if (isScalarFPTypeInSSEReg(SrcVT))
22682     return Op;
22683 
22684   return LRINT_LLRINTHelper(Op.getNode(), DAG);
22685 }
22686 
22687 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
22688                                               SelectionDAG &DAG) const {
22689   EVT DstVT = N->getValueType(0);
22690   SDValue Src = N->getOperand(0);
22691   EVT SrcVT = Src.getValueType();
22692 
22693   if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
22694     // f16 must be promoted before using the lowering in this routine.
22695     // fp128 does not use this lowering.
22696     return SDValue();
22697   }
22698 
22699   SDLoc DL(N);
22700   SDValue Chain = DAG.getEntryNode();
22701 
22702   bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
22703 
22704   // If we're converting from SSE, the stack slot needs to hold both types.
22705   // Otherwise it only needs to hold the DstVT.
22706   EVT OtherVT = UseSSE ? SrcVT : DstVT;
22707   SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
22708   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
22709   MachinePointerInfo MPI =
22710       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
22711 
22712   if (UseSSE) {
22713     assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
22714     Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
22715     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
22716     SDValue Ops[] = { Chain, StackPtr };
22717 
22718     Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
22719                                   /*Align*/ None, MachineMemOperand::MOLoad);
22720     Chain = Src.getValue(1);
22721   }
22722 
22723   SDValue StoreOps[] = { Chain, Src, StackPtr };
22724   Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
22725                                   StoreOps, DstVT, MPI, /*Align*/ None,
22726                                   MachineMemOperand::MOStore);
22727 
22728   return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
22729 }
22730 
22731 SDValue
22732 X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
22733   // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
22734   // but making use of X86 specifics to produce better instruction sequences.
22735   SDNode *Node = Op.getNode();
22736   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
22737   unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
22738   SDLoc dl(SDValue(Node, 0));
22739   SDValue Src = Node->getOperand(0);
22740 
22741   // There are three types involved here: SrcVT is the source floating point
22742   // type, DstVT is the type of the result, and TmpVT is the result of the
22743   // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
22744   // DstVT).
22745   EVT SrcVT = Src.getValueType();
22746   EVT DstVT = Node->getValueType(0);
22747   EVT TmpVT = DstVT;
22748 
22749   // This code is only for floats and doubles. Fall back to generic code for
22750   // anything else.
22751   if (!isScalarFPTypeInSSEReg(SrcVT) || isSoftFP16(SrcVT))
22752     return SDValue();
22753 
22754   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
22755   unsigned SatWidth = SatVT.getScalarSizeInBits();
22756   unsigned DstWidth = DstVT.getScalarSizeInBits();
22757   unsigned TmpWidth = TmpVT.getScalarSizeInBits();
22758   assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&
22759          "Expected saturation width smaller than result width");
22760 
22761   // Promote result of FP_TO_*INT to at least 32 bits.
22762   if (TmpWidth < 32) {
22763     TmpVT = MVT::i32;
22764     TmpWidth = 32;
22765   }
22766 
22767   // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
22768   // us to use a native signed conversion instead.
22769   if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
22770     TmpVT = MVT::i64;
22771     TmpWidth = 64;
22772   }
22773 
22774   // If the saturation width is smaller than the size of the temporary result,
22775   // we can always use signed conversion, which is native.
22776   if (SatWidth < TmpWidth)
22777     FpToIntOpcode = ISD::FP_TO_SINT;
22778 
22779   // Determine minimum and maximum integer values and their corresponding
22780   // floating-point values.
22781   APInt MinInt, MaxInt;
22782   if (IsSigned) {
22783     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
22784     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
22785   } else {
22786     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
22787     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
22788   }
22789 
22790   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
22791   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
22792 
22793   APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
22794     MinInt, IsSigned, APFloat::rmTowardZero);
22795   APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
22796     MaxInt, IsSigned, APFloat::rmTowardZero);
22797   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
22798                           && !(MaxStatus & APFloat::opStatus::opInexact);
22799 
22800   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
22801   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
22802 
22803   // If the integer bounds are exactly representable as floats, emit a
22804   // min+max+fptoi sequence. Otherwise use comparisons and selects.
22805   if (AreExactFloatBounds) {
22806     if (DstVT != TmpVT) {
22807       // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
22808       SDValue MinClamped = DAG.getNode(
22809         X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
22810       // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
22811       SDValue BothClamped = DAG.getNode(
22812         X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
22813       // Convert clamped value to integer.
22814       SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
22815 
22816       // NaN will become INDVAL, with the top bit set and the rest zero.
22817       // Truncation will discard the top bit, resulting in zero.
22818       return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
22819     }
22820 
22821     // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
22822     SDValue MinClamped = DAG.getNode(
22823       X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
22824     // Clamp by MaxFloat from above. NaN cannot occur.
22825     SDValue BothClamped = DAG.getNode(
22826       X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
22827     // Convert clamped value to integer.
22828     SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
22829 
22830     if (!IsSigned) {
22831       // In the unsigned case we're done, because we mapped NaN to MinFloat,
22832       // which is zero.
22833       return FpToInt;
22834     }
22835 
22836     // Otherwise, select zero if Src is NaN.
22837     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
22838     return DAG.getSelectCC(
22839       dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
22840   }
22841 
22842   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
22843   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
22844 
22845   // Result of direct conversion, which may be selected away.
22846   SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
22847 
22848   if (DstVT != TmpVT) {
22849     // NaN will become INDVAL, with the top bit set and the rest zero.
22850     // Truncation will discard the top bit, resulting in zero.
22851     FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
22852   }
22853 
22854   SDValue Select = FpToInt;
22855   // For signed conversions where we saturate to the same size as the
22856   // result type of the fptoi instructions, INDVAL coincides with integer
22857   // minimum, so we don't need to explicitly check it.
22858   if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
22859     // If Src ULT MinFloat, select MinInt. In particular, this also selects
22860     // MinInt if Src is NaN.
22861     Select = DAG.getSelectCC(
22862       dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
22863   }
22864 
22865   // If Src OGT MaxFloat, select MaxInt.
22866   Select = DAG.getSelectCC(
22867     dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
22868 
22869   // In the unsigned case we are done, because we mapped NaN to MinInt, which
22870   // is already zero. The promoted case was already handled above.
22871   if (!IsSigned || DstVT != TmpVT) {
22872     return Select;
22873   }
22874 
22875   // Otherwise, select 0 if Src is NaN.
22876   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
22877   return DAG.getSelectCC(
22878     dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
22879 }
22880 
22881 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
22882   bool IsStrict = Op->isStrictFPOpcode();
22883 
22884   SDLoc DL(Op);
22885   MVT VT = Op.getSimpleValueType();
22886   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
22887   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
22888   MVT SVT = In.getSimpleValueType();
22889 
22890   if (VT == MVT::f128 || (SVT == MVT::f16 && VT == MVT::f80))
22891     return SDValue();
22892 
22893   if (SVT == MVT::f16) {
22894     if (Subtarget.hasFP16())
22895       return Op;
22896 
22897     if (VT != MVT::f32) {
22898       if (IsStrict)
22899         return DAG.getNode(
22900             ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other},
22901             {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, DL,
22902                                 {MVT::f32, MVT::Other}, {Chain, In})});
22903 
22904       return DAG.getNode(ISD::FP_EXTEND, DL, VT,
22905                          DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, In));
22906     }
22907 
22908     if (!Subtarget.hasF16C())
22909       return SDValue();
22910 
22911     In = DAG.getBitcast(MVT::i16, In);
22912     In = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16,
22913                      getZeroVector(MVT::v8i16, Subtarget, DAG, DL), In,
22914                      DAG.getIntPtrConstant(0, DL));
22915     SDValue Res;
22916     if (IsStrict) {
22917       Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, DL, {MVT::v4f32, MVT::Other},
22918                         {Chain, In});
22919       Chain = Res.getValue(1);
22920     } else {
22921       Res = DAG.getNode(X86ISD::CVTPH2PS, DL, MVT::v4f32, In,
22922                         DAG.getTargetConstant(4, DL, MVT::i32));
22923     }
22924     Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Res,
22925                       DAG.getIntPtrConstant(0, DL));
22926     if (IsStrict)
22927       return DAG.getMergeValues({Res, Chain}, DL);
22928     return Res;
22929   }
22930 
22931   if (!SVT.isVector())
22932     return Op;
22933 
22934   if (SVT.getVectorElementType() == MVT::f16) {
22935     assert(Subtarget.hasF16C() && "Unexpected features!");
22936     if (SVT == MVT::v2f16)
22937       In = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f16, In,
22938                        DAG.getUNDEF(MVT::v2f16));
22939     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f16, In,
22940                               DAG.getUNDEF(MVT::v4f16));
22941     if (IsStrict)
22942       return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
22943                          {Op->getOperand(0), Res});
22944     return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
22945   } else if (VT == MVT::v4f64 || VT == MVT::v8f64) {
22946     return Op;
22947   }
22948 
22949   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
22950 
22951   SDValue Res =
22952       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
22953   if (IsStrict)
22954     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
22955                        {Op->getOperand(0), Res});
22956   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
22957 }
22958 
22959 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
22960   bool IsStrict = Op->isStrictFPOpcode();
22961 
22962   SDLoc DL(Op);
22963   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
22964   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
22965   MVT VT = Op.getSimpleValueType();
22966   MVT SVT = In.getSimpleValueType();
22967 
22968   if (SVT == MVT::f128 || (VT == MVT::f16 && SVT == MVT::f80))
22969     return SDValue();
22970 
22971   if (VT.getScalarType() == MVT::f16 && !Subtarget.hasFP16()) {
22972     if (!Subtarget.hasF16C() || SVT.getScalarType() != MVT::f32)
22973       return SDValue();
22974 
22975     if (VT.isVector())
22976       return Op;
22977 
22978     SDValue Res;
22979     SDValue Rnd = DAG.getTargetConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, DL,
22980                                         MVT::i32);
22981     if (IsStrict) {
22982       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4f32,
22983                         DAG.getConstantFP(0, DL, MVT::v4f32), In,
22984                         DAG.getIntPtrConstant(0, DL));
22985       Res = DAG.getNode(X86ISD::STRICT_CVTPS2PH, DL, {MVT::v8i16, MVT::Other},
22986                         {Chain, Res, Rnd});
22987       Chain = Res.getValue(1);
22988     } else {
22989       // FIXME: Should we use zeros for upper elements for non-strict?
22990       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, In);
22991       Res = DAG.getNode(X86ISD::CVTPS2PH, DL, MVT::v8i16, Res, Rnd);
22992     }
22993 
22994     Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i16, Res,
22995                       DAG.getIntPtrConstant(0, DL));
22996     Res = DAG.getBitcast(MVT::f16, Res);
22997 
22998     if (IsStrict)
22999       return DAG.getMergeValues({Res, Chain}, DL);
23000 
23001     return Res;
23002   }
23003 
23004   return Op;
23005 }
23006 
23007 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
23008   bool IsStrict = Op->isStrictFPOpcode();
23009   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
23010   assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
23011          "Unexpected VT!");
23012 
23013   SDLoc dl(Op);
23014   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
23015                             DAG.getConstant(0, dl, MVT::v8i16), Src,
23016                             DAG.getIntPtrConstant(0, dl));
23017 
23018   SDValue Chain;
23019   if (IsStrict) {
23020     Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
23021                       {Op.getOperand(0), Res});
23022     Chain = Res.getValue(1);
23023   } else {
23024     Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
23025   }
23026 
23027   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
23028                     DAG.getIntPtrConstant(0, dl));
23029 
23030   if (IsStrict)
23031     return DAG.getMergeValues({Res, Chain}, dl);
23032 
23033   return Res;
23034 }
23035 
23036 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
23037   bool IsStrict = Op->isStrictFPOpcode();
23038   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
23039   assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
23040          "Unexpected VT!");
23041 
23042   SDLoc dl(Op);
23043   SDValue Res, Chain;
23044   if (IsStrict) {
23045     Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
23046                       DAG.getConstantFP(0, dl, MVT::v4f32), Src,
23047                       DAG.getIntPtrConstant(0, dl));
23048     Res = DAG.getNode(
23049         X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
23050         {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
23051     Chain = Res.getValue(1);
23052   } else {
23053     // FIXME: Should we use zeros for upper elements for non-strict?
23054     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
23055     Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
23056                       DAG.getTargetConstant(4, dl, MVT::i32));
23057   }
23058 
23059   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
23060                     DAG.getIntPtrConstant(0, dl));
23061 
23062   if (IsStrict)
23063     return DAG.getMergeValues({Res, Chain}, dl);
23064 
23065   return Res;
23066 }
23067 
23068 SDValue X86TargetLowering::LowerFP_TO_BF16(SDValue Op,
23069                                            SelectionDAG &DAG) const {
23070   SDLoc DL(Op);
23071   MakeLibCallOptions CallOptions;
23072   RTLIB::Libcall LC =
23073       RTLIB::getFPROUND(Op.getOperand(0).getValueType(), MVT::bf16);
23074   SDValue Res =
23075       makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
23076   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i16,
23077                      DAG.getBitcast(MVT::i32, Res));
23078 }
23079 
23080 /// Depending on uarch and/or optimizing for size, we might prefer to use a
23081 /// vector operation in place of the typical scalar operation.
23082 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
23083                                          const X86Subtarget &Subtarget) {
23084   // If both operands have other uses, this is probably not profitable.
23085   SDValue LHS = Op.getOperand(0);
23086   SDValue RHS = Op.getOperand(1);
23087   if (!LHS.hasOneUse() && !RHS.hasOneUse())
23088     return Op;
23089 
23090   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
23091   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
23092   if (IsFP && !Subtarget.hasSSE3())
23093     return Op;
23094   if (!IsFP && !Subtarget.hasSSSE3())
23095     return Op;
23096 
23097   // Extract from a common vector.
23098   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
23099       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
23100       LHS.getOperand(0) != RHS.getOperand(0) ||
23101       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
23102       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
23103       !shouldUseHorizontalOp(true, DAG, Subtarget))
23104     return Op;
23105 
23106   // Allow commuted 'hadd' ops.
23107   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
23108   unsigned HOpcode;
23109   switch (Op.getOpcode()) {
23110     case ISD::ADD: HOpcode = X86ISD::HADD; break;
23111     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
23112     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
23113     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
23114     default:
23115       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
23116   }
23117   unsigned LExtIndex = LHS.getConstantOperandVal(1);
23118   unsigned RExtIndex = RHS.getConstantOperandVal(1);
23119   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
23120       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
23121     std::swap(LExtIndex, RExtIndex);
23122 
23123   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
23124     return Op;
23125 
23126   SDValue X = LHS.getOperand(0);
23127   EVT VecVT = X.getValueType();
23128   unsigned BitWidth = VecVT.getSizeInBits();
23129   unsigned NumLanes = BitWidth / 128;
23130   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
23131   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
23132          "Not expecting illegal vector widths here");
23133 
23134   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
23135   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
23136   SDLoc DL(Op);
23137   if (BitWidth == 256 || BitWidth == 512) {
23138     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
23139     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
23140     LExtIndex %= NumEltsPerLane;
23141   }
23142 
23143   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
23144   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
23145   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
23146   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
23147   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
23148   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
23149                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
23150 }
23151 
23152 /// Depending on uarch and/or optimizing for size, we might prefer to use a
23153 /// vector operation in place of the typical scalar operation.
23154 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
23155   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
23156          "Only expecting float/double");
23157   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
23158 }
23159 
23160 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
23161 /// This mode isn't supported in hardware on X86. But as long as we aren't
23162 /// compiling with trapping math, we can emulate this with
23163 /// trunc(X + copysign(nextafter(0.5, 0.0), X)).
23164 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
23165   SDValue N0 = Op.getOperand(0);
23166   SDLoc dl(Op);
23167   MVT VT = Op.getSimpleValueType();
23168 
23169   // N0 += copysign(nextafter(0.5, 0.0), N0)
23170   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
23171   bool Ignored;
23172   APFloat Point5Pred = APFloat(0.5f);
23173   Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
23174   Point5Pred.next(/*nextDown*/true);
23175 
23176   SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
23177                               DAG.getConstantFP(Point5Pred, dl, VT), N0);
23178   N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
23179 
23180   // Truncate the result to remove fraction.
23181   return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
23182 }
23183 
23184 /// The only differences between FABS and FNEG are the mask and the logic op.
23185 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
23186 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
23187   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
23188          "Wrong opcode for lowering FABS or FNEG.");
23189 
23190   bool IsFABS = (Op.getOpcode() == ISD::FABS);
23191 
23192   // If this is a FABS and it has an FNEG user, bail out to fold the combination
23193   // into an FNABS. We'll lower the FABS after that if it is still in use.
23194   if (IsFABS)
23195     for (SDNode *User : Op->uses())
23196       if (User->getOpcode() == ISD::FNEG)
23197         return Op;
23198 
23199   SDLoc dl(Op);
23200   MVT VT = Op.getSimpleValueType();
23201 
23202   bool IsF128 = (VT == MVT::f128);
23203   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
23204          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
23205          "Unexpected type in LowerFABSorFNEG");
23206 
23207   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
23208   // decide if we should generate a 16-byte constant mask when we only need 4 or
23209   // 8 bytes for the scalar case.
23210 
23211   // There are no scalar bitwise logical SSE/AVX instructions, so we
23212   // generate a 16-byte vector constant and logic op even for the scalar case.
23213   // Using a 16-byte mask allows folding the load of the mask with
23214   // the logic op, so it can save (~4 bytes) on code size.
23215   bool IsFakeVector = !VT.isVector() && !IsF128;
23216   MVT LogicVT = VT;
23217   if (IsFakeVector)
23218     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
23219               : (VT == MVT::f32) ? MVT::v4f32
23220                                  : MVT::v8f16;
23221 
23222   unsigned EltBits = VT.getScalarSizeInBits();
23223   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
23224   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
23225                            APInt::getSignMask(EltBits);
23226   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
23227   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
23228 
23229   SDValue Op0 = Op.getOperand(0);
23230   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
23231   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
23232                      IsFNABS ? X86ISD::FOR  :
23233                                X86ISD::FXOR;
23234   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
23235 
23236   if (VT.isVector() || IsF128)
23237     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
23238 
23239   // For the scalar case extend to a 128-bit vector, perform the logic op,
23240   // and extract the scalar result back out.
23241   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
23242   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
23243   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
23244                      DAG.getIntPtrConstant(0, dl));
23245 }
23246 
23247 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
23248   SDValue Mag = Op.getOperand(0);
23249   SDValue Sign = Op.getOperand(1);
23250   SDLoc dl(Op);
23251 
23252   // If the sign operand is smaller, extend it first.
23253   MVT VT = Op.getSimpleValueType();
23254   if (Sign.getSimpleValueType().bitsLT(VT))
23255     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
23256 
23257   // And if it is bigger, shrink it first.
23258   if (Sign.getSimpleValueType().bitsGT(VT))
23259     Sign =
23260         DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(0, dl));
23261 
23262   // At this point the operands and the result should have the same
23263   // type, and that won't be f80 since that is not custom lowered.
23264   bool IsF128 = (VT == MVT::f128);
23265   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
23266          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
23267          "Unexpected type in LowerFCOPYSIGN");
23268 
23269   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
23270 
23271   // Perform all scalar logic operations as 16-byte vectors because there are no
23272   // scalar FP logic instructions in SSE.
23273   // TODO: This isn't necessary. If we used scalar types, we might avoid some
23274   // unnecessary splats, but we might miss load folding opportunities. Should
23275   // this decision be based on OptimizeForSize?
23276   bool IsFakeVector = !VT.isVector() && !IsF128;
23277   MVT LogicVT = VT;
23278   if (IsFakeVector)
23279     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
23280               : (VT == MVT::f32) ? MVT::v4f32
23281                                  : MVT::v8f16;
23282 
23283   // The mask constants are automatically splatted for vector types.
23284   unsigned EltSizeInBits = VT.getScalarSizeInBits();
23285   SDValue SignMask = DAG.getConstantFP(
23286       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
23287   SDValue MagMask = DAG.getConstantFP(
23288       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
23289 
23290   // First, clear all bits but the sign bit from the second operand (sign).
23291   if (IsFakeVector)
23292     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
23293   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
23294 
23295   // Next, clear the sign bit from the first operand (magnitude).
23296   // TODO: If we had general constant folding for FP logic ops, this check
23297   // wouldn't be necessary.
23298   SDValue MagBits;
23299   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
23300     APFloat APF = Op0CN->getValueAPF();
23301     APF.clearSign();
23302     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
23303   } else {
23304     // If the magnitude operand wasn't a constant, we need to AND out the sign.
23305     if (IsFakeVector)
23306       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
23307     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
23308   }
23309 
23310   // OR the magnitude value with the sign bit.
23311   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
23312   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
23313                                           DAG.getIntPtrConstant(0, dl));
23314 }
23315 
23316 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
23317   SDValue N0 = Op.getOperand(0);
23318   SDLoc dl(Op);
23319   MVT VT = Op.getSimpleValueType();
23320 
23321   MVT OpVT = N0.getSimpleValueType();
23322   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
23323          "Unexpected type for FGETSIGN");
23324 
23325   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
23326   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
23327   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
23328   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
23329   Res = DAG.getZExtOrTrunc(Res, dl, VT);
23330   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
23331   return Res;
23332 }
23333 
23334 /// Helper for attempting to create a X86ISD::BT node.
23335 static SDValue getBT(SDValue Src, SDValue BitNo, const SDLoc &DL, SelectionDAG &DAG) {
23336   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
23337   // instruction.  Since the shift amount is in-range-or-undefined, we know
23338   // that doing a bittest on the i32 value is ok.  We extend to i32 because
23339   // the encoding for the i16 version is larger than the i32 version.
23340   // Also promote i16 to i32 for performance / code size reason.
23341   if (Src.getValueType().getScalarSizeInBits() < 32)
23342     Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
23343 
23344   // No legal type found, give up.
23345   if (!DAG.getTargetLoweringInfo().isTypeLegal(Src.getValueType()))
23346     return SDValue();
23347 
23348   // See if we can use the 32-bit instruction instead of the 64-bit one for a
23349   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
23350   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
23351   // known to be zero.
23352   if (Src.getValueType() == MVT::i64 &&
23353       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
23354     Src = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
23355 
23356   // If the operand types disagree, extend the shift amount to match.  Since
23357   // BT ignores high bits (like shifts) we can use anyextend.
23358   if (Src.getValueType() != BitNo.getValueType()) {
23359     // Peek through a mask/modulo operation.
23360     // TODO: DAGCombine fails to do this as it just checks isTruncateFree, but
23361     // we probably need a better IsDesirableToPromoteOp to handle this as well.
23362     if (BitNo.getOpcode() == ISD::AND && BitNo->hasOneUse())
23363       BitNo = DAG.getNode(ISD::AND, DL, Src.getValueType(),
23364                           DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
23365                                       BitNo.getOperand(0)),
23366                           DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
23367                                       BitNo.getOperand(1)));
23368     else
23369       BitNo = DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(), BitNo);
23370   }
23371 
23372   return DAG.getNode(X86ISD::BT, DL, MVT::i32, Src, BitNo);
23373 }
23374 
23375 /// Helper for creating a X86ISD::SETCC node.
23376 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
23377                         SelectionDAG &DAG) {
23378   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
23379                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
23380 }
23381 
23382 /// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
23383 /// style scalarized (associative) reduction patterns. Partial reductions
23384 /// are supported when the pointer SrcMask is non-null.
23385 /// TODO - move this to SelectionDAG?
23386 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
23387                                  SmallVectorImpl<SDValue> &SrcOps,
23388                                  SmallVectorImpl<APInt> *SrcMask = nullptr) {
23389   SmallVector<SDValue, 8> Opnds;
23390   DenseMap<SDValue, APInt> SrcOpMap;
23391   EVT VT = MVT::Other;
23392 
23393   // Recognize a special case where a vector is casted into wide integer to
23394   // test all 0s.
23395   assert(Op.getOpcode() == unsigned(BinOp) &&
23396          "Unexpected bit reduction opcode");
23397   Opnds.push_back(Op.getOperand(0));
23398   Opnds.push_back(Op.getOperand(1));
23399 
23400   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
23401     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
23402     // BFS traverse all BinOp operands.
23403     if (I->getOpcode() == unsigned(BinOp)) {
23404       Opnds.push_back(I->getOperand(0));
23405       Opnds.push_back(I->getOperand(1));
23406       // Re-evaluate the number of nodes to be traversed.
23407       e += 2; // 2 more nodes (LHS and RHS) are pushed.
23408       continue;
23409     }
23410 
23411     // Quit if a non-EXTRACT_VECTOR_ELT
23412     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23413       return false;
23414 
23415     // Quit if without a constant index.
23416     auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
23417     if (!Idx)
23418       return false;
23419 
23420     SDValue Src = I->getOperand(0);
23421     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
23422     if (M == SrcOpMap.end()) {
23423       VT = Src.getValueType();
23424       // Quit if not the same type.
23425       if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
23426         return false;
23427       unsigned NumElts = VT.getVectorNumElements();
23428       APInt EltCount = APInt::getZero(NumElts);
23429       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
23430       SrcOps.push_back(Src);
23431     }
23432 
23433     // Quit if element already used.
23434     unsigned CIdx = Idx->getZExtValue();
23435     if (M->second[CIdx])
23436       return false;
23437     M->second.setBit(CIdx);
23438   }
23439 
23440   if (SrcMask) {
23441     // Collect the source partial masks.
23442     for (SDValue &SrcOp : SrcOps)
23443       SrcMask->push_back(SrcOpMap[SrcOp]);
23444   } else {
23445     // Quit if not all elements are used.
23446     for (const auto &I : SrcOpMap)
23447       if (!I.second.isAllOnes())
23448         return false;
23449   }
23450 
23451   return true;
23452 }
23453 
23454 // Helper function for comparing all bits of a vector against zero.
23455 static SDValue LowerVectorAllZero(const SDLoc &DL, SDValue V, ISD::CondCode CC,
23456                                   const APInt &Mask,
23457                                   const X86Subtarget &Subtarget,
23458                                   SelectionDAG &DAG, X86::CondCode &X86CC) {
23459   EVT VT = V.getValueType();
23460   unsigned ScalarSize = VT.getScalarSizeInBits();
23461   if (Mask.getBitWidth() != ScalarSize) {
23462     assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch");
23463     return SDValue();
23464   }
23465 
23466   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
23467   X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
23468 
23469   auto MaskBits = [&](SDValue Src) {
23470     if (Mask.isAllOnes())
23471       return Src;
23472     EVT SrcVT = Src.getValueType();
23473     SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
23474     return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
23475   };
23476 
23477   // For sub-128-bit vector, cast to (legal) integer and compare with zero.
23478   if (VT.getSizeInBits() < 128) {
23479     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
23480     if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT))
23481       return SDValue();
23482     return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
23483                        DAG.getBitcast(IntVT, MaskBits(V)),
23484                        DAG.getConstant(0, DL, IntVT));
23485   }
23486 
23487   // Quit if not splittable to 128/256-bit vector.
23488   if (!isPowerOf2_32(VT.getSizeInBits()))
23489     return SDValue();
23490 
23491   // Split down to 128/256-bit vector.
23492   unsigned TestSize = Subtarget.hasAVX() ? 256 : 128;
23493   while (VT.getSizeInBits() > TestSize) {
23494     auto Split = DAG.SplitVector(V, DL);
23495     VT = Split.first.getValueType();
23496     V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
23497   }
23498 
23499   bool UsePTEST = Subtarget.hasSSE41();
23500   if (UsePTEST) {
23501     MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
23502     V = DAG.getBitcast(TestVT, MaskBits(V));
23503     return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
23504   }
23505 
23506   // Without PTEST, a masked v2i64 or-reduction is not faster than
23507   // scalarization.
23508   if (!Mask.isAllOnes() && VT.getScalarSizeInBits() > 32)
23509     return SDValue();
23510 
23511   V = DAG.getBitcast(MVT::v16i8, MaskBits(V));
23512   V = DAG.getNode(X86ISD::PCMPEQ, DL, MVT::v16i8, V,
23513                   getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
23514   V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
23515   return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
23516                      DAG.getConstant(0xFFFF, DL, MVT::i32));
23517 }
23518 
23519 // Check whether an OR'd reduction tree is PTEST-able, or if we can fallback to
23520 // CMP(MOVMSK(PCMPEQB(X,0))).
23521 static SDValue MatchVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
23522                                       const SDLoc &DL,
23523                                       const X86Subtarget &Subtarget,
23524                                       SelectionDAG &DAG, SDValue &X86CC) {
23525   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
23526 
23527   if (!Subtarget.hasSSE2() || !Op->hasOneUse())
23528     return SDValue();
23529 
23530   // Check whether we're masking/truncating an OR-reduction result, in which
23531   // case track the masked bits.
23532   APInt Mask = APInt::getAllOnes(Op.getScalarValueSizeInBits());
23533   switch (Op.getOpcode()) {
23534   case ISD::TRUNCATE: {
23535     SDValue Src = Op.getOperand(0);
23536     Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
23537                                 Op.getScalarValueSizeInBits());
23538     Op = Src;
23539     break;
23540   }
23541   case ISD::AND: {
23542     if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23543       Mask = Cst->getAPIntValue();
23544       Op = Op.getOperand(0);
23545     }
23546     break;
23547   }
23548   }
23549 
23550   SmallVector<SDValue, 8> VecIns;
23551   if (Op.getOpcode() == ISD::OR && matchScalarReduction(Op, ISD::OR, VecIns)) {
23552     EVT VT = VecIns[0].getValueType();
23553     assert(llvm::all_of(VecIns,
23554                         [VT](SDValue V) { return VT == V.getValueType(); }) &&
23555            "Reduction source vector mismatch");
23556 
23557     // Quit if less than 128-bits or not splittable to 128/256-bit vector.
23558     if (VT.getSizeInBits() < 128 || !isPowerOf2_32(VT.getSizeInBits()))
23559       return SDValue();
23560 
23561     // If more than one full vector is evaluated, OR them first before PTEST.
23562     for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
23563          Slot += 2, e += 1) {
23564       // Each iteration will OR 2 nodes and append the result until there is
23565       // only 1 node left, i.e. the final OR'd value of all vectors.
23566       SDValue LHS = VecIns[Slot];
23567       SDValue RHS = VecIns[Slot + 1];
23568       VecIns.push_back(DAG.getNode(ISD::OR, DL, VT, LHS, RHS));
23569     }
23570 
23571     X86::CondCode CCode;
23572     if (SDValue V = LowerVectorAllZero(DL, VecIns.back(), CC, Mask, Subtarget,
23573                                        DAG, CCode)) {
23574       X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
23575       return V;
23576     }
23577   }
23578 
23579   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23580     ISD::NodeType BinOp;
23581     if (SDValue Match =
23582             DAG.matchBinOpReduction(Op.getNode(), BinOp, {ISD::OR})) {
23583       X86::CondCode CCode;
23584       if (SDValue V =
23585               LowerVectorAllZero(DL, Match, CC, Mask, Subtarget, DAG, CCode)) {
23586         X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
23587         return V;
23588       }
23589     }
23590   }
23591 
23592   return SDValue();
23593 }
23594 
23595 /// return true if \c Op has a use that doesn't just read flags.
23596 static bool hasNonFlagsUse(SDValue Op) {
23597   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
23598        ++UI) {
23599     SDNode *User = *UI;
23600     unsigned UOpNo = UI.getOperandNo();
23601     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
23602       // Look pass truncate.
23603       UOpNo = User->use_begin().getOperandNo();
23604       User = *User->use_begin();
23605     }
23606 
23607     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
23608         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
23609       return true;
23610   }
23611   return false;
23612 }
23613 
23614 // Transform to an x86-specific ALU node with flags if there is a chance of
23615 // using an RMW op or only the flags are used. Otherwise, leave
23616 // the node alone and emit a 'cmp' or 'test' instruction.
23617 static bool isProfitableToUseFlagOp(SDValue Op) {
23618   for (SDNode *U : Op->uses())
23619     if (U->getOpcode() != ISD::CopyToReg &&
23620         U->getOpcode() != ISD::SETCC &&
23621         U->getOpcode() != ISD::STORE)
23622       return false;
23623 
23624   return true;
23625 }
23626 
23627 /// Emit nodes that will be selected as "test Op0,Op0", or something
23628 /// equivalent.
23629 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
23630                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
23631   // CF and OF aren't always set the way we want. Determine which
23632   // of these we need.
23633   bool NeedCF = false;
23634   bool NeedOF = false;
23635   switch (X86CC) {
23636   default: break;
23637   case X86::COND_A: case X86::COND_AE:
23638   case X86::COND_B: case X86::COND_BE:
23639     NeedCF = true;
23640     break;
23641   case X86::COND_G: case X86::COND_GE:
23642   case X86::COND_L: case X86::COND_LE:
23643   case X86::COND_O: case X86::COND_NO: {
23644     // Check if we really need to set the
23645     // Overflow flag. If NoSignedWrap is present
23646     // that is not actually needed.
23647     switch (Op->getOpcode()) {
23648     case ISD::ADD:
23649     case ISD::SUB:
23650     case ISD::MUL:
23651     case ISD::SHL:
23652       if (Op.getNode()->getFlags().hasNoSignedWrap())
23653         break;
23654       LLVM_FALLTHROUGH;
23655     default:
23656       NeedOF = true;
23657       break;
23658     }
23659     break;
23660   }
23661   }
23662   // See if we can use the EFLAGS value from the operand instead of
23663   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
23664   // we prove that the arithmetic won't overflow, we can't use OF or CF.
23665   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
23666     // Emit a CMP with 0, which is the TEST pattern.
23667     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
23668                        DAG.getConstant(0, dl, Op.getValueType()));
23669   }
23670   unsigned Opcode = 0;
23671   unsigned NumOperands = 0;
23672 
23673   SDValue ArithOp = Op;
23674 
23675   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
23676   // which may be the result of a CAST.  We use the variable 'Op', which is the
23677   // non-casted variable when we check for possible users.
23678   switch (ArithOp.getOpcode()) {
23679   case ISD::AND:
23680     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
23681     // because a TEST instruction will be better.
23682     if (!hasNonFlagsUse(Op))
23683       break;
23684 
23685     LLVM_FALLTHROUGH;
23686   case ISD::ADD:
23687   case ISD::SUB:
23688   case ISD::OR:
23689   case ISD::XOR:
23690     if (!isProfitableToUseFlagOp(Op))
23691       break;
23692 
23693     // Otherwise use a regular EFLAGS-setting instruction.
23694     switch (ArithOp.getOpcode()) {
23695     default: llvm_unreachable("unexpected operator!");
23696     case ISD::ADD: Opcode = X86ISD::ADD; break;
23697     case ISD::SUB: Opcode = X86ISD::SUB; break;
23698     case ISD::XOR: Opcode = X86ISD::XOR; break;
23699     case ISD::AND: Opcode = X86ISD::AND; break;
23700     case ISD::OR:  Opcode = X86ISD::OR;  break;
23701     }
23702 
23703     NumOperands = 2;
23704     break;
23705   case X86ISD::ADD:
23706   case X86ISD::SUB:
23707   case X86ISD::OR:
23708   case X86ISD::XOR:
23709   case X86ISD::AND:
23710     return SDValue(Op.getNode(), 1);
23711   case ISD::SSUBO:
23712   case ISD::USUBO: {
23713     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
23714     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23715     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
23716                        Op->getOperand(1)).getValue(1);
23717   }
23718   default:
23719     break;
23720   }
23721 
23722   if (Opcode == 0) {
23723     // Emit a CMP with 0, which is the TEST pattern.
23724     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
23725                        DAG.getConstant(0, dl, Op.getValueType()));
23726   }
23727   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23728   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
23729 
23730   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
23731   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
23732   return SDValue(New.getNode(), 1);
23733 }
23734 
23735 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
23736 /// equivalent.
23737 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
23738                        const SDLoc &dl, SelectionDAG &DAG,
23739                        const X86Subtarget &Subtarget) {
23740   if (isNullConstant(Op1))
23741     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
23742 
23743   EVT CmpVT = Op0.getValueType();
23744 
23745   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
23746           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
23747 
23748   // Only promote the compare up to I32 if it is a 16 bit operation
23749   // with an immediate.  16 bit immediates are to be avoided.
23750   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
23751       !DAG.getMachineFunction().getFunction().hasMinSize()) {
23752     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
23753     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
23754     // Don't do this if the immediate can fit in 8-bits.
23755     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
23756         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
23757       unsigned ExtendOp =
23758           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
23759       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
23760         // For equality comparisons try to use SIGN_EXTEND if the input was
23761         // truncate from something with enough sign bits.
23762         if (Op0.getOpcode() == ISD::TRUNCATE) {
23763           if (DAG.ComputeMaxSignificantBits(Op0.getOperand(0)) <= 16)
23764             ExtendOp = ISD::SIGN_EXTEND;
23765         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
23766           if (DAG.ComputeMaxSignificantBits(Op1.getOperand(0)) <= 16)
23767             ExtendOp = ISD::SIGN_EXTEND;
23768         }
23769       }
23770 
23771       CmpVT = MVT::i32;
23772       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
23773       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
23774     }
23775   }
23776 
23777   // Try to shrink i64 compares if the input has enough zero bits.
23778   // FIXME: Do this for non-constant compares for constant on LHS?
23779   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
23780       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
23781       cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
23782       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
23783     CmpVT = MVT::i32;
23784     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
23785     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
23786   }
23787 
23788   // 0-x == y --> x+y == 0
23789   // 0-x != y --> x+y != 0
23790   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
23791       Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
23792     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23793     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
23794     return Add.getValue(1);
23795   }
23796 
23797   // x == 0-y --> x+y == 0
23798   // x != 0-y --> x+y != 0
23799   if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
23800       Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
23801     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23802     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
23803     return Add.getValue(1);
23804   }
23805 
23806   // Use SUB instead of CMP to enable CSE between SUB and CMP.
23807   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23808   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
23809   return Sub.getValue(1);
23810 }
23811 
23812 /// Check if replacement of SQRT with RSQRT should be disabled.
23813 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
23814   EVT VT = Op.getValueType();
23815 
23816   // We don't need to replace SQRT with RSQRT for half type.
23817   if (VT.getScalarType() == MVT::f16)
23818     return true;
23819 
23820   // We never want to use both SQRT and RSQRT instructions for the same input.
23821   if (DAG.doesNodeExist(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
23822     return false;
23823 
23824   if (VT.isVector())
23825     return Subtarget.hasFastVectorFSQRT();
23826   return Subtarget.hasFastScalarFSQRT();
23827 }
23828 
23829 /// The minimum architected relative accuracy is 2^-12. We need one
23830 /// Newton-Raphson step to have a good float result (24 bits of precision).
23831 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
23832                                            SelectionDAG &DAG, int Enabled,
23833                                            int &RefinementSteps,
23834                                            bool &UseOneConstNR,
23835                                            bool Reciprocal) const {
23836   SDLoc DL(Op);
23837   EVT VT = Op.getValueType();
23838 
23839   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
23840   // It is likely not profitable to do this for f64 because a double-precision
23841   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
23842   // instructions: convert to single, rsqrtss, convert back to double, refine
23843   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
23844   // along with FMA, this could be a throughput win.
23845   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
23846   // after legalize types.
23847   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
23848       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
23849       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
23850       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
23851       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
23852     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23853       RefinementSteps = 1;
23854 
23855     UseOneConstNR = false;
23856     // There is no FSQRT for 512-bits, but there is RSQRT14.
23857     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
23858     SDValue Estimate = DAG.getNode(Opcode, DL, VT, Op);
23859     if (RefinementSteps == 0 && !Reciprocal)
23860       Estimate = DAG.getNode(ISD::FMUL, DL, VT, Op, Estimate);
23861     return Estimate;
23862   }
23863 
23864   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
23865       Subtarget.hasFP16()) {
23866     assert(Reciprocal && "Don't replace SQRT with RSQRT for half type");
23867     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23868       RefinementSteps = 0;
23869 
23870     if (VT == MVT::f16) {
23871       SDValue Zero = DAG.getIntPtrConstant(0, DL);
23872       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
23873       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
23874       Op = DAG.getNode(X86ISD::RSQRT14S, DL, MVT::v8f16, Undef, Op);
23875       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
23876     }
23877 
23878     return DAG.getNode(X86ISD::RSQRT14, DL, VT, Op);
23879   }
23880   return SDValue();
23881 }
23882 
23883 /// The minimum architected relative accuracy is 2^-12. We need one
23884 /// Newton-Raphson step to have a good float result (24 bits of precision).
23885 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
23886                                             int Enabled,
23887                                             int &RefinementSteps) const {
23888   SDLoc DL(Op);
23889   EVT VT = Op.getValueType();
23890 
23891   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
23892   // It is likely not profitable to do this for f64 because a double-precision
23893   // reciprocal estimate with refinement on x86 prior to FMA requires
23894   // 15 instructions: convert to single, rcpss, convert back to double, refine
23895   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
23896   // along with FMA, this could be a throughput win.
23897 
23898   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
23899       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
23900       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
23901       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
23902     // Enable estimate codegen with 1 refinement step for vector division.
23903     // Scalar division estimates are disabled because they break too much
23904     // real-world code. These defaults are intended to match GCC behavior.
23905     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
23906       return SDValue();
23907 
23908     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23909       RefinementSteps = 1;
23910 
23911     // There is no FSQRT for 512-bits, but there is RCP14.
23912     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
23913     return DAG.getNode(Opcode, DL, VT, Op);
23914   }
23915 
23916   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
23917       Subtarget.hasFP16()) {
23918     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23919       RefinementSteps = 0;
23920 
23921     if (VT == MVT::f16) {
23922       SDValue Zero = DAG.getIntPtrConstant(0, DL);
23923       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
23924       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
23925       Op = DAG.getNode(X86ISD::RCP14S, DL, MVT::v8f16, Undef, Op);
23926       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
23927     }
23928 
23929     return DAG.getNode(X86ISD::RCP14, DL, VT, Op);
23930   }
23931   return SDValue();
23932 }
23933 
23934 /// If we have at least two divisions that use the same divisor, convert to
23935 /// multiplication by a reciprocal. This may need to be adjusted for a given
23936 /// CPU if a division's cost is not at least twice the cost of a multiplication.
23937 /// This is because we still need one division to calculate the reciprocal and
23938 /// then we need two multiplies by that reciprocal as replacements for the
23939 /// original divisions.
23940 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
23941   return 2;
23942 }
23943 
23944 SDValue
23945 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
23946                                  SelectionDAG &DAG,
23947                                  SmallVectorImpl<SDNode *> &Created) const {
23948   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
23949   if (isIntDivCheap(N->getValueType(0), Attr))
23950     return SDValue(N,0); // Lower SDIV as SDIV
23951 
23952   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
23953          "Unexpected divisor!");
23954 
23955   // Only perform this transform if CMOV is supported otherwise the select
23956   // below will become a branch.
23957   if (!Subtarget.canUseCMOV())
23958     return SDValue();
23959 
23960   // fold (sdiv X, pow2)
23961   EVT VT = N->getValueType(0);
23962   // FIXME: Support i8.
23963   if (VT != MVT::i16 && VT != MVT::i32 &&
23964       !(Subtarget.is64Bit() && VT == MVT::i64))
23965     return SDValue();
23966 
23967   unsigned Lg2 = Divisor.countTrailingZeros();
23968 
23969   // If the divisor is 2 or -2, the default expansion is better.
23970   if (Lg2 == 1)
23971     return SDValue();
23972 
23973   SDLoc DL(N);
23974   SDValue N0 = N->getOperand(0);
23975   SDValue Zero = DAG.getConstant(0, DL, VT);
23976   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
23977   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
23978 
23979   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
23980   SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
23981   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
23982   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
23983 
23984   Created.push_back(Cmp.getNode());
23985   Created.push_back(Add.getNode());
23986   Created.push_back(CMov.getNode());
23987 
23988   // Divide by pow2.
23989   SDValue SRA =
23990       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
23991 
23992   // If we're dividing by a positive value, we're done.  Otherwise, we must
23993   // negate the result.
23994   if (Divisor.isNonNegative())
23995     return SRA;
23996 
23997   Created.push_back(SRA.getNode());
23998   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
23999 }
24000 
24001 /// Result of 'and' is compared against zero. Change to a BT node if possible.
24002 /// Returns the BT node and the condition code needed to use it.
24003 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC, const SDLoc &dl,
24004                             SelectionDAG &DAG, X86::CondCode &X86CC) {
24005   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
24006   SDValue Op0 = And.getOperand(0);
24007   SDValue Op1 = And.getOperand(1);
24008   if (Op0.getOpcode() == ISD::TRUNCATE)
24009     Op0 = Op0.getOperand(0);
24010   if (Op1.getOpcode() == ISD::TRUNCATE)
24011     Op1 = Op1.getOperand(0);
24012 
24013   SDValue Src, BitNo;
24014   if (Op1.getOpcode() == ISD::SHL)
24015     std::swap(Op0, Op1);
24016   if (Op0.getOpcode() == ISD::SHL) {
24017     if (isOneConstant(Op0.getOperand(0))) {
24018       // If we looked past a truncate, check that it's only truncating away
24019       // known zeros.
24020       unsigned BitWidth = Op0.getValueSizeInBits();
24021       unsigned AndBitWidth = And.getValueSizeInBits();
24022       if (BitWidth > AndBitWidth) {
24023         KnownBits Known = DAG.computeKnownBits(Op0);
24024         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
24025           return SDValue();
24026       }
24027       Src = Op1;
24028       BitNo = Op0.getOperand(1);
24029     }
24030   } else if (Op1.getOpcode() == ISD::Constant) {
24031     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
24032     uint64_t AndRHSVal = AndRHS->getZExtValue();
24033     SDValue AndLHS = Op0;
24034 
24035     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
24036       Src = AndLHS.getOperand(0);
24037       BitNo = AndLHS.getOperand(1);
24038     } else {
24039       // Use BT if the immediate can't be encoded in a TEST instruction or we
24040       // are optimizing for size and the immedaite won't fit in a byte.
24041       bool OptForSize = DAG.shouldOptForSize();
24042       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
24043           isPowerOf2_64(AndRHSVal)) {
24044         Src = AndLHS;
24045         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
24046                                 Src.getValueType());
24047       }
24048     }
24049   }
24050 
24051   // No patterns found, give up.
24052   if (!Src.getNode())
24053     return SDValue();
24054 
24055   // Remove any bit flip.
24056   if (isBitwiseNot(Src)) {
24057     Src = Src.getOperand(0);
24058     CC = CC == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
24059   }
24060 
24061   // Attempt to create the X86ISD::BT node.
24062   if (SDValue BT = getBT(Src, BitNo, dl, DAG)) {
24063     X86CC = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
24064     return BT;
24065   }
24066 
24067   return SDValue();
24068 }
24069 
24070 // Check if pre-AVX condcode can be performed by a single FCMP op.
24071 static bool cheapX86FSETCC_SSE(ISD::CondCode SetCCOpcode) {
24072   return (SetCCOpcode != ISD::SETONE) && (SetCCOpcode != ISD::SETUEQ);
24073 }
24074 
24075 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
24076 /// CMPs.
24077 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
24078                                    SDValue &Op1, bool &IsAlwaysSignaling) {
24079   unsigned SSECC;
24080   bool Swap = false;
24081 
24082   // SSE Condition code mapping:
24083   //  0 - EQ
24084   //  1 - LT
24085   //  2 - LE
24086   //  3 - UNORD
24087   //  4 - NEQ
24088   //  5 - NLT
24089   //  6 - NLE
24090   //  7 - ORD
24091   switch (SetCCOpcode) {
24092   default: llvm_unreachable("Unexpected SETCC condition");
24093   case ISD::SETOEQ:
24094   case ISD::SETEQ:  SSECC = 0; break;
24095   case ISD::SETOGT:
24096   case ISD::SETGT:  Swap = true; LLVM_FALLTHROUGH;
24097   case ISD::SETLT:
24098   case ISD::SETOLT: SSECC = 1; break;
24099   case ISD::SETOGE:
24100   case ISD::SETGE:  Swap = true; LLVM_FALLTHROUGH;
24101   case ISD::SETLE:
24102   case ISD::SETOLE: SSECC = 2; break;
24103   case ISD::SETUO:  SSECC = 3; break;
24104   case ISD::SETUNE:
24105   case ISD::SETNE:  SSECC = 4; break;
24106   case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
24107   case ISD::SETUGE: SSECC = 5; break;
24108   case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
24109   case ISD::SETUGT: SSECC = 6; break;
24110   case ISD::SETO:   SSECC = 7; break;
24111   case ISD::SETUEQ: SSECC = 8; break;
24112   case ISD::SETONE: SSECC = 12; break;
24113   }
24114   if (Swap)
24115     std::swap(Op0, Op1);
24116 
24117   switch (SetCCOpcode) {
24118   default:
24119     IsAlwaysSignaling = true;
24120     break;
24121   case ISD::SETEQ:
24122   case ISD::SETOEQ:
24123   case ISD::SETUEQ:
24124   case ISD::SETNE:
24125   case ISD::SETONE:
24126   case ISD::SETUNE:
24127   case ISD::SETO:
24128   case ISD::SETUO:
24129     IsAlwaysSignaling = false;
24130     break;
24131   }
24132 
24133   return SSECC;
24134 }
24135 
24136 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
24137 /// concatenate the result back.
24138 static SDValue splitIntVSETCC(EVT VT, SDValue LHS, SDValue RHS,
24139                               ISD::CondCode Cond, SelectionDAG &DAG,
24140                               const SDLoc &dl) {
24141   assert(VT.isInteger() && VT == LHS.getValueType() &&
24142          VT == RHS.getValueType() && "Unsupported VTs!");
24143 
24144   SDValue CC = DAG.getCondCode(Cond);
24145 
24146   // Extract the LHS Lo/Hi vectors
24147   SDValue LHS1, LHS2;
24148   std::tie(LHS1, LHS2) = splitVector(LHS, DAG, dl);
24149 
24150   // Extract the RHS Lo/Hi vectors
24151   SDValue RHS1, RHS2;
24152   std::tie(RHS1, RHS2) = splitVector(RHS, DAG, dl);
24153 
24154   // Issue the operation on the smaller types and concatenate the result back
24155   EVT LoVT, HiVT;
24156   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
24157   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
24158                      DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
24159                      DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
24160 }
24161 
24162 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
24163 
24164   SDValue Op0 = Op.getOperand(0);
24165   SDValue Op1 = Op.getOperand(1);
24166   SDValue CC = Op.getOperand(2);
24167   MVT VT = Op.getSimpleValueType();
24168   SDLoc dl(Op);
24169 
24170   assert(VT.getVectorElementType() == MVT::i1 &&
24171          "Cannot set masked compare for this operation");
24172 
24173   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
24174 
24175   // Prefer SETGT over SETLT.
24176   if (SetCCOpcode == ISD::SETLT) {
24177     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
24178     std::swap(Op0, Op1);
24179   }
24180 
24181   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
24182 }
24183 
24184 /// Given a buildvector constant, return a new vector constant with each element
24185 /// incremented or decremented. If incrementing or decrementing would result in
24186 /// unsigned overflow or underflow or this is not a simple vector constant,
24187 /// return an empty value.
24188 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
24189   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
24190   if (!BV)
24191     return SDValue();
24192 
24193   MVT VT = V.getSimpleValueType();
24194   MVT EltVT = VT.getVectorElementType();
24195   unsigned NumElts = VT.getVectorNumElements();
24196   SmallVector<SDValue, 8> NewVecC;
24197   SDLoc DL(V);
24198   for (unsigned i = 0; i < NumElts; ++i) {
24199     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
24200     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
24201       return SDValue();
24202 
24203     // Avoid overflow/underflow.
24204     const APInt &EltC = Elt->getAPIntValue();
24205     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isZero()))
24206       return SDValue();
24207 
24208     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
24209   }
24210 
24211   return DAG.getBuildVector(VT, DL, NewVecC);
24212 }
24213 
24214 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
24215 /// Op0 u<= Op1:
24216 ///   t = psubus Op0, Op1
24217 ///   pcmpeq t, <0..0>
24218 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
24219                                     ISD::CondCode Cond, const SDLoc &dl,
24220                                     const X86Subtarget &Subtarget,
24221                                     SelectionDAG &DAG) {
24222   if (!Subtarget.hasSSE2())
24223     return SDValue();
24224 
24225   MVT VET = VT.getVectorElementType();
24226   if (VET != MVT::i8 && VET != MVT::i16)
24227     return SDValue();
24228 
24229   switch (Cond) {
24230   default:
24231     return SDValue();
24232   case ISD::SETULT: {
24233     // If the comparison is against a constant we can turn this into a
24234     // setule.  With psubus, setule does not require a swap.  This is
24235     // beneficial because the constant in the register is no longer
24236     // destructed as the destination so it can be hoisted out of a loop.
24237     // Only do this pre-AVX since vpcmp* is no longer destructive.
24238     if (Subtarget.hasAVX())
24239       return SDValue();
24240     SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false);
24241     if (!ULEOp1)
24242       return SDValue();
24243     Op1 = ULEOp1;
24244     break;
24245   }
24246   case ISD::SETUGT: {
24247     // If the comparison is against a constant, we can turn this into a setuge.
24248     // This is beneficial because materializing a constant 0 for the PCMPEQ is
24249     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
24250     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
24251     SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true);
24252     if (!UGEOp1)
24253       return SDValue();
24254     Op1 = Op0;
24255     Op0 = UGEOp1;
24256     break;
24257   }
24258   // Psubus is better than flip-sign because it requires no inversion.
24259   case ISD::SETUGE:
24260     std::swap(Op0, Op1);
24261     break;
24262   case ISD::SETULE:
24263     break;
24264   }
24265 
24266   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
24267   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
24268                      DAG.getConstant(0, dl, VT));
24269 }
24270 
24271 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
24272                            SelectionDAG &DAG) {
24273   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
24274                   Op.getOpcode() == ISD::STRICT_FSETCCS;
24275   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
24276   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
24277   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
24278   MVT VT = Op->getSimpleValueType(0);
24279   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
24280   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
24281   SDLoc dl(Op);
24282 
24283   if (isFP) {
24284     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
24285     assert(EltVT == MVT::f16 || EltVT == MVT::f32 || EltVT == MVT::f64);
24286     if (isSoftFP16(EltVT, Subtarget))
24287       return SDValue();
24288 
24289     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
24290     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
24291 
24292     // If we have a strict compare with a vXi1 result and the input is 128/256
24293     // bits we can't use a masked compare unless we have VLX. If we use a wider
24294     // compare like we do for non-strict, we might trigger spurious exceptions
24295     // from the upper elements. Instead emit a AVX compare and convert to mask.
24296     unsigned Opc;
24297     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
24298         (!IsStrict || Subtarget.hasVLX() ||
24299          Op0.getSimpleValueType().is512BitVector())) {
24300 #ifndef NDEBUG
24301       unsigned Num = VT.getVectorNumElements();
24302       assert(Num <= 16 || (Num == 32 && EltVT == MVT::f16));
24303 #endif
24304       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
24305     } else {
24306       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
24307       // The SSE/AVX packed FP comparison nodes are defined with a
24308       // floating-point vector result that matches the operand type. This allows
24309       // them to work with an SSE1 target (integer vector types are not legal).
24310       VT = Op0.getSimpleValueType();
24311     }
24312 
24313     SDValue Cmp;
24314     bool IsAlwaysSignaling;
24315     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
24316     if (!Subtarget.hasAVX()) {
24317       // TODO: We could use following steps to handle a quiet compare with
24318       // signaling encodings.
24319       // 1. Get ordered masks from a quiet ISD::SETO
24320       // 2. Use the masks to mask potential unordered elements in operand A, B
24321       // 3. Get the compare results of masked A, B
24322       // 4. Calculating final result using the mask and result from 3
24323       // But currently, we just fall back to scalar operations.
24324       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
24325         return SDValue();
24326 
24327       // Insert an extra signaling instruction to raise exception.
24328       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
24329         SDValue SignalCmp = DAG.getNode(
24330             Opc, dl, {VT, MVT::Other},
24331             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
24332         // FIXME: It seems we need to update the flags of all new strict nodes.
24333         // Otherwise, mayRaiseFPException in MI will return false due to
24334         // NoFPExcept = false by default. However, I didn't find it in other
24335         // patches.
24336         SignalCmp->setFlags(Op->getFlags());
24337         Chain = SignalCmp.getValue(1);
24338       }
24339 
24340       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
24341       // emit two comparisons and a logic op to tie them together.
24342       if (!cheapX86FSETCC_SSE(Cond)) {
24343         // LLVM predicate is SETUEQ or SETONE.
24344         unsigned CC0, CC1;
24345         unsigned CombineOpc;
24346         if (Cond == ISD::SETUEQ) {
24347           CC0 = 3; // UNORD
24348           CC1 = 0; // EQ
24349           CombineOpc = X86ISD::FOR;
24350         } else {
24351           assert(Cond == ISD::SETONE);
24352           CC0 = 7; // ORD
24353           CC1 = 4; // NEQ
24354           CombineOpc = X86ISD::FAND;
24355         }
24356 
24357         SDValue Cmp0, Cmp1;
24358         if (IsStrict) {
24359           Cmp0 = DAG.getNode(
24360               Opc, dl, {VT, MVT::Other},
24361               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
24362           Cmp1 = DAG.getNode(
24363               Opc, dl, {VT, MVT::Other},
24364               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
24365           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
24366                               Cmp1.getValue(1));
24367         } else {
24368           Cmp0 = DAG.getNode(
24369               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
24370           Cmp1 = DAG.getNode(
24371               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
24372         }
24373         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
24374       } else {
24375         if (IsStrict) {
24376           Cmp = DAG.getNode(
24377               Opc, dl, {VT, MVT::Other},
24378               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
24379           Chain = Cmp.getValue(1);
24380         } else
24381           Cmp = DAG.getNode(
24382               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
24383       }
24384     } else {
24385       // Handle all other FP comparisons here.
24386       if (IsStrict) {
24387         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
24388         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
24389         Cmp = DAG.getNode(
24390             Opc, dl, {VT, MVT::Other},
24391             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
24392         Chain = Cmp.getValue(1);
24393       } else
24394         Cmp = DAG.getNode(
24395             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
24396     }
24397 
24398     if (VT.getFixedSizeInBits() >
24399         Op.getSimpleValueType().getFixedSizeInBits()) {
24400       // We emitted a compare with an XMM/YMM result. Finish converting to a
24401       // mask register using a vptestm.
24402       EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
24403       Cmp = DAG.getBitcast(CastVT, Cmp);
24404       Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
24405                          DAG.getConstant(0, dl, CastVT), ISD::SETNE);
24406     } else {
24407       // If this is SSE/AVX CMPP, bitcast the result back to integer to match
24408       // the result type of SETCC. The bitcast is expected to be optimized
24409       // away during combining/isel.
24410       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
24411     }
24412 
24413     if (IsStrict)
24414       return DAG.getMergeValues({Cmp, Chain}, dl);
24415 
24416     return Cmp;
24417   }
24418 
24419   assert(!IsStrict && "Strict SETCC only handles FP operands.");
24420 
24421   MVT VTOp0 = Op0.getSimpleValueType();
24422   (void)VTOp0;
24423   assert(VTOp0 == Op1.getSimpleValueType() &&
24424          "Expected operands with same type!");
24425   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
24426          "Invalid number of packed elements for source and destination!");
24427 
24428   // The non-AVX512 code below works under the assumption that source and
24429   // destination types are the same.
24430   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
24431          "Value types for source and destination must be the same!");
24432 
24433   // The result is boolean, but operands are int/float
24434   if (VT.getVectorElementType() == MVT::i1) {
24435     // In AVX-512 architecture setcc returns mask with i1 elements,
24436     // But there is no compare instruction for i8 and i16 elements in KNL.
24437     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
24438            "Unexpected operand type");
24439     return LowerIntVSETCC_AVX512(Op, DAG);
24440   }
24441 
24442   // Lower using XOP integer comparisons.
24443   if (VT.is128BitVector() && Subtarget.hasXOP()) {
24444     // Translate compare code to XOP PCOM compare mode.
24445     unsigned CmpMode = 0;
24446     switch (Cond) {
24447     default: llvm_unreachable("Unexpected SETCC condition");
24448     case ISD::SETULT:
24449     case ISD::SETLT: CmpMode = 0x00; break;
24450     case ISD::SETULE:
24451     case ISD::SETLE: CmpMode = 0x01; break;
24452     case ISD::SETUGT:
24453     case ISD::SETGT: CmpMode = 0x02; break;
24454     case ISD::SETUGE:
24455     case ISD::SETGE: CmpMode = 0x03; break;
24456     case ISD::SETEQ: CmpMode = 0x04; break;
24457     case ISD::SETNE: CmpMode = 0x05; break;
24458     }
24459 
24460     // Are we comparing unsigned or signed integers?
24461     unsigned Opc =
24462         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
24463 
24464     return DAG.getNode(Opc, dl, VT, Op0, Op1,
24465                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
24466   }
24467 
24468   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
24469   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
24470   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
24471     SDValue BC0 = peekThroughBitcasts(Op0);
24472     if (BC0.getOpcode() == ISD::AND) {
24473       APInt UndefElts;
24474       SmallVector<APInt, 64> EltBits;
24475       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
24476                                         VT.getScalarSizeInBits(), UndefElts,
24477                                         EltBits, false, false)) {
24478         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
24479           Cond = ISD::SETEQ;
24480           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
24481         }
24482       }
24483     }
24484   }
24485 
24486   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
24487   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
24488       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
24489     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
24490     if (C1 && C1->getAPIntValue().isPowerOf2()) {
24491       unsigned BitWidth = VT.getScalarSizeInBits();
24492       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
24493 
24494       SDValue Result = Op0.getOperand(0);
24495       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
24496                            DAG.getConstant(ShiftAmt, dl, VT));
24497       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
24498                            DAG.getConstant(BitWidth - 1, dl, VT));
24499       return Result;
24500     }
24501   }
24502 
24503   // Break 256-bit integer vector compare into smaller ones.
24504   if (VT.is256BitVector() && !Subtarget.hasInt256())
24505     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
24506 
24507   // Break 512-bit integer vector compare into smaller ones.
24508   // TODO: Try harder to use VPCMPx + VPMOV2x?
24509   if (VT.is512BitVector())
24510     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
24511 
24512   // If we have a limit constant, try to form PCMPGT (signed cmp) to avoid
24513   // not-of-PCMPEQ:
24514   // X != INT_MIN --> X >s INT_MIN
24515   // X != INT_MAX --> X <s INT_MAX --> INT_MAX >s X
24516   // +X != 0 --> +X >s 0
24517   APInt ConstValue;
24518   if (Cond == ISD::SETNE &&
24519       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
24520     if (ConstValue.isMinSignedValue())
24521       Cond = ISD::SETGT;
24522     else if (ConstValue.isMaxSignedValue())
24523       Cond = ISD::SETLT;
24524     else if (ConstValue.isZero() && DAG.SignBitIsZero(Op0))
24525       Cond = ISD::SETGT;
24526   }
24527 
24528   // If both operands are known non-negative, then an unsigned compare is the
24529   // same as a signed compare and there's no need to flip signbits.
24530   // TODO: We could check for more general simplifications here since we're
24531   // computing known bits.
24532   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
24533                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
24534 
24535   // Special case: Use min/max operations for unsigned compares.
24536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24537   if (ISD::isUnsignedIntSetCC(Cond) &&
24538       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
24539       TLI.isOperationLegal(ISD::UMIN, VT)) {
24540     // If we have a constant operand, increment/decrement it and change the
24541     // condition to avoid an invert.
24542     if (Cond == ISD::SETUGT) {
24543       // X > C --> X >= (C+1) --> X == umax(X, C+1)
24544       if (SDValue UGTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true)) {
24545         Op1 = UGTOp1;
24546         Cond = ISD::SETUGE;
24547       }
24548     }
24549     if (Cond == ISD::SETULT) {
24550       // X < C --> X <= (C-1) --> X == umin(X, C-1)
24551       if (SDValue ULTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false)) {
24552         Op1 = ULTOp1;
24553         Cond = ISD::SETULE;
24554       }
24555     }
24556     bool Invert = false;
24557     unsigned Opc;
24558     switch (Cond) {
24559     default: llvm_unreachable("Unexpected condition code");
24560     case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH;
24561     case ISD::SETULE: Opc = ISD::UMIN; break;
24562     case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH;
24563     case ISD::SETUGE: Opc = ISD::UMAX; break;
24564     }
24565 
24566     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
24567     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
24568 
24569     // If the logical-not of the result is required, perform that now.
24570     if (Invert)
24571       Result = DAG.getNOT(dl, Result, VT);
24572 
24573     return Result;
24574   }
24575 
24576   // Try to use SUBUS and PCMPEQ.
24577   if (FlipSigns)
24578     if (SDValue V =
24579             LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
24580       return V;
24581 
24582   // We are handling one of the integer comparisons here. Since SSE only has
24583   // GT and EQ comparisons for integer, swapping operands and multiple
24584   // operations may be required for some comparisons.
24585   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
24586                                                             : X86ISD::PCMPGT;
24587   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
24588               Cond == ISD::SETGE || Cond == ISD::SETUGE;
24589   bool Invert = Cond == ISD::SETNE ||
24590                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
24591 
24592   if (Swap)
24593     std::swap(Op0, Op1);
24594 
24595   // Check that the operation in question is available (most are plain SSE2,
24596   // but PCMPGTQ and PCMPEQQ have different requirements).
24597   if (VT == MVT::v2i64) {
24598     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
24599       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
24600 
24601       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
24602       // the odd elements over the even elements.
24603       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
24604         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
24605         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
24606 
24607         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
24608         static const int MaskHi[] = { 1, 1, 3, 3 };
24609         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
24610 
24611         return DAG.getBitcast(VT, Result);
24612       }
24613 
24614       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
24615         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
24616         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
24617 
24618         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
24619         static const int MaskHi[] = { 1, 1, 3, 3 };
24620         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
24621 
24622         return DAG.getBitcast(VT, Result);
24623       }
24624 
24625       // Since SSE has no unsigned integer comparisons, we need to flip the sign
24626       // bits of the inputs before performing those operations. The lower
24627       // compare is always unsigned.
24628       SDValue SB = DAG.getConstant(FlipSigns ? 0x8000000080000000ULL
24629                                              : 0x0000000080000000ULL,
24630                                    dl, MVT::v2i64);
24631 
24632       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
24633       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
24634 
24635       // Cast everything to the right type.
24636       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
24637       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
24638 
24639       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
24640       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
24641       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
24642 
24643       // Create masks for only the low parts/high parts of the 64 bit integers.
24644       static const int MaskHi[] = { 1, 1, 3, 3 };
24645       static const int MaskLo[] = { 0, 0, 2, 2 };
24646       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
24647       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
24648       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
24649 
24650       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
24651       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
24652 
24653       if (Invert)
24654         Result = DAG.getNOT(dl, Result, MVT::v4i32);
24655 
24656       return DAG.getBitcast(VT, Result);
24657     }
24658 
24659     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
24660       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
24661       // pcmpeqd + pshufd + pand.
24662       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
24663 
24664       // First cast everything to the right type.
24665       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
24666       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
24667 
24668       // Do the compare.
24669       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
24670 
24671       // Make sure the lower and upper halves are both all-ones.
24672       static const int Mask[] = { 1, 0, 3, 2 };
24673       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
24674       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
24675 
24676       if (Invert)
24677         Result = DAG.getNOT(dl, Result, MVT::v4i32);
24678 
24679       return DAG.getBitcast(VT, Result);
24680     }
24681   }
24682 
24683   // Since SSE has no unsigned integer comparisons, we need to flip the sign
24684   // bits of the inputs before performing those operations.
24685   if (FlipSigns) {
24686     MVT EltVT = VT.getVectorElementType();
24687     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
24688                                  VT);
24689     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
24690     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
24691   }
24692 
24693   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
24694 
24695   // If the logical-not of the result is required, perform that now.
24696   if (Invert)
24697     Result = DAG.getNOT(dl, Result, VT);
24698 
24699   return Result;
24700 }
24701 
24702 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
24703 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
24704                               const SDLoc &dl, SelectionDAG &DAG,
24705                               const X86Subtarget &Subtarget,
24706                               SDValue &X86CC) {
24707   // Only support equality comparisons.
24708   if (CC != ISD::SETEQ && CC != ISD::SETNE)
24709     return SDValue();
24710 
24711   // Must be a bitcast from vXi1.
24712   if (Op0.getOpcode() != ISD::BITCAST)
24713     return SDValue();
24714 
24715   Op0 = Op0.getOperand(0);
24716   MVT VT = Op0.getSimpleValueType();
24717   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
24718       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
24719       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
24720     return SDValue();
24721 
24722   X86::CondCode X86Cond;
24723   if (isNullConstant(Op1)) {
24724     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
24725   } else if (isAllOnesConstant(Op1)) {
24726     // C flag is set for all ones.
24727     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
24728   } else
24729     return SDValue();
24730 
24731   // If the input is an AND, we can combine it's operands into the KTEST.
24732   bool KTestable = false;
24733   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
24734     KTestable = true;
24735   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
24736     KTestable = true;
24737   if (!isNullConstant(Op1))
24738     KTestable = false;
24739   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
24740     SDValue LHS = Op0.getOperand(0);
24741     SDValue RHS = Op0.getOperand(1);
24742     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24743     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
24744   }
24745 
24746   // If the input is an OR, we can combine it's operands into the KORTEST.
24747   SDValue LHS = Op0;
24748   SDValue RHS = Op0;
24749   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
24750     LHS = Op0.getOperand(0);
24751     RHS = Op0.getOperand(1);
24752   }
24753 
24754   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24755   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
24756 }
24757 
24758 /// Emit flags for the given setcc condition and operands. Also returns the
24759 /// corresponding X86 condition code constant in X86CC.
24760 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
24761                                              ISD::CondCode CC, const SDLoc &dl,
24762                                              SelectionDAG &DAG,
24763                                              SDValue &X86CC) const {
24764   // Optimize to BT if possible.
24765   // Lower (X & (1 << N)) == 0 to BT(X, N).
24766   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
24767   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
24768   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
24769       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
24770     X86::CondCode X86CondCode;
24771     if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CondCode)) {
24772       X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
24773       return BT;
24774     }
24775   }
24776 
24777   // Try to use PTEST/PMOVMSKB for a tree ORs equality compared with 0.
24778   // TODO: We could do AND tree with all 1s as well by using the C flag.
24779   if (isNullConstant(Op1) && (CC == ISD::SETEQ || CC == ISD::SETNE))
24780     if (SDValue CmpZ =
24781             MatchVectorAllZeroTest(Op0, CC, dl, Subtarget, DAG, X86CC))
24782       return CmpZ;
24783 
24784   // Try to lower using KORTEST or KTEST.
24785   if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
24786     return Test;
24787 
24788   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
24789   // these.
24790   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
24791       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
24792     // If the input is a setcc, then reuse the input setcc or use a new one with
24793     // the inverted condition.
24794     if (Op0.getOpcode() == X86ISD::SETCC) {
24795       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
24796 
24797       X86CC = Op0.getOperand(0);
24798       if (Invert) {
24799         X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
24800         CCode = X86::GetOppositeBranchCondition(CCode);
24801         X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
24802       }
24803 
24804       return Op0.getOperand(1);
24805     }
24806   }
24807 
24808   // Try to use the carry flag from the add in place of an separate CMP for:
24809   // (seteq (add X, -1), -1). Similar for setne.
24810   if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
24811       Op0.getOperand(1) == Op1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
24812     if (isProfitableToUseFlagOp(Op0)) {
24813       SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
24814 
24815       SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
24816                                 Op0.getOperand(1));
24817       DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
24818       X86::CondCode CCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
24819       X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
24820       return SDValue(New.getNode(), 1);
24821     }
24822   }
24823 
24824   X86::CondCode CondCode =
24825       TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
24826   assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
24827 
24828   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
24829   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24830   return EFLAGS;
24831 }
24832 
24833 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
24834 
24835   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
24836                   Op.getOpcode() == ISD::STRICT_FSETCCS;
24837   MVT VT = Op->getSimpleValueType(0);
24838 
24839   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
24840 
24841   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
24842   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
24843   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
24844   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
24845   SDLoc dl(Op);
24846   ISD::CondCode CC =
24847       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
24848 
24849   if (isSoftFP16(Op0.getValueType()))
24850     return SDValue();
24851 
24852   // Handle f128 first, since one possible outcome is a normal integer
24853   // comparison which gets handled by emitFlagsForSetcc.
24854   if (Op0.getValueType() == MVT::f128) {
24855     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
24856                         Op.getOpcode() == ISD::STRICT_FSETCCS);
24857 
24858     // If softenSetCCOperands returned a scalar, use it.
24859     if (!Op1.getNode()) {
24860       assert(Op0.getValueType() == Op.getValueType() &&
24861              "Unexpected setcc expansion!");
24862       if (IsStrict)
24863         return DAG.getMergeValues({Op0, Chain}, dl);
24864       return Op0;
24865     }
24866   }
24867 
24868   if (Op0.getSimpleValueType().isInteger()) {
24869     // Attempt to canonicalize SGT/UGT -> SGE/UGE compares with constant which
24870     // reduces the number of EFLAGs bit reads (the GE conditions don't read ZF),
24871     // this may translate to less uops depending on uarch implementation. The
24872     // equivalent for SLE/ULE -> SLT/ULT isn't likely to happen as we already
24873     // canonicalize to that CondCode.
24874     // NOTE: Only do this if incrementing the constant doesn't increase the bit
24875     // encoding size - so it must either already be a i8 or i32 immediate, or it
24876     // shrinks down to that. We don't do this for any i64's to avoid additional
24877     // constant materializations.
24878     // TODO: Can we move this to TranslateX86CC to handle jumps/branches too?
24879     if (auto *Op1C = dyn_cast<ConstantSDNode>(Op1)) {
24880       const APInt &Op1Val = Op1C->getAPIntValue();
24881       if (!Op1Val.isZero()) {
24882         // Ensure the constant+1 doesn't overflow.
24883         if ((CC == ISD::CondCode::SETGT && !Op1Val.isMaxSignedValue()) ||
24884             (CC == ISD::CondCode::SETUGT && !Op1Val.isMaxValue())) {
24885           APInt Op1ValPlusOne = Op1Val + 1;
24886           if (Op1ValPlusOne.isSignedIntN(32) &&
24887               (!Op1Val.isSignedIntN(8) || Op1ValPlusOne.isSignedIntN(8))) {
24888             Op1 = DAG.getConstant(Op1ValPlusOne, dl, Op0.getValueType());
24889             CC = CC == ISD::CondCode::SETGT ? ISD::CondCode::SETGE
24890                                             : ISD::CondCode::SETUGE;
24891           }
24892         }
24893       }
24894     }
24895 
24896     SDValue X86CC;
24897     SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
24898     SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
24899     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
24900   }
24901 
24902   // Handle floating point.
24903   X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
24904   if (CondCode == X86::COND_INVALID)
24905     return SDValue();
24906 
24907   SDValue EFLAGS;
24908   if (IsStrict) {
24909     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
24910     EFLAGS =
24911         DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
24912                     dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
24913     Chain = EFLAGS.getValue(1);
24914   } else {
24915     EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
24916   }
24917 
24918   SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24919   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
24920   return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
24921 }
24922 
24923 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
24924   SDValue LHS = Op.getOperand(0);
24925   SDValue RHS = Op.getOperand(1);
24926   SDValue Carry = Op.getOperand(2);
24927   SDValue Cond = Op.getOperand(3);
24928   SDLoc DL(Op);
24929 
24930   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
24931   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
24932 
24933   // Recreate the carry if needed.
24934   EVT CarryVT = Carry.getValueType();
24935   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
24936                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
24937 
24938   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
24939   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
24940   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
24941 }
24942 
24943 // This function returns three things: the arithmetic computation itself
24944 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
24945 // flag and the condition code define the case in which the arithmetic
24946 // computation overflows.
24947 static std::pair<SDValue, SDValue>
24948 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
24949   assert(Op.getResNo() == 0 && "Unexpected result number!");
24950   SDValue Value, Overflow;
24951   SDValue LHS = Op.getOperand(0);
24952   SDValue RHS = Op.getOperand(1);
24953   unsigned BaseOp = 0;
24954   SDLoc DL(Op);
24955   switch (Op.getOpcode()) {
24956   default: llvm_unreachable("Unknown ovf instruction!");
24957   case ISD::SADDO:
24958     BaseOp = X86ISD::ADD;
24959     Cond = X86::COND_O;
24960     break;
24961   case ISD::UADDO:
24962     BaseOp = X86ISD::ADD;
24963     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
24964     break;
24965   case ISD::SSUBO:
24966     BaseOp = X86ISD::SUB;
24967     Cond = X86::COND_O;
24968     break;
24969   case ISD::USUBO:
24970     BaseOp = X86ISD::SUB;
24971     Cond = X86::COND_B;
24972     break;
24973   case ISD::SMULO:
24974     BaseOp = X86ISD::SMUL;
24975     Cond = X86::COND_O;
24976     break;
24977   case ISD::UMULO:
24978     BaseOp = X86ISD::UMUL;
24979     Cond = X86::COND_O;
24980     break;
24981   }
24982 
24983   if (BaseOp) {
24984     // Also sets EFLAGS.
24985     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
24986     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
24987     Overflow = Value.getValue(1);
24988   }
24989 
24990   return std::make_pair(Value, Overflow);
24991 }
24992 
24993 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
24994   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
24995   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
24996   // looks for this combo and may remove the "setcc" instruction if the "setcc"
24997   // has only one use.
24998   SDLoc DL(Op);
24999   X86::CondCode Cond;
25000   SDValue Value, Overflow;
25001   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
25002 
25003   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
25004   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
25005   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
25006 }
25007 
25008 /// Return true if opcode is a X86 logical comparison.
25009 static bool isX86LogicalCmp(SDValue Op) {
25010   unsigned Opc = Op.getOpcode();
25011   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
25012       Opc == X86ISD::FCMP)
25013     return true;
25014   if (Op.getResNo() == 1 &&
25015       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
25016        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
25017        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
25018     return true;
25019 
25020   return false;
25021 }
25022 
25023 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
25024   if (V.getOpcode() != ISD::TRUNCATE)
25025     return false;
25026 
25027   SDValue VOp0 = V.getOperand(0);
25028   unsigned InBits = VOp0.getValueSizeInBits();
25029   unsigned Bits = V.getValueSizeInBits();
25030   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
25031 }
25032 
25033 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
25034   bool AddTest = true;
25035   SDValue Cond  = Op.getOperand(0);
25036   SDValue Op1 = Op.getOperand(1);
25037   SDValue Op2 = Op.getOperand(2);
25038   SDLoc DL(Op);
25039   MVT VT = Op1.getSimpleValueType();
25040   SDValue CC;
25041 
25042   if (isSoftFP16(VT)) {
25043     MVT NVT = VT.changeTypeToInteger();
25044     return DAG.getBitcast(VT, DAG.getNode(ISD::SELECT, DL, NVT, Cond,
25045                                           DAG.getBitcast(NVT, Op1),
25046                                           DAG.getBitcast(NVT, Op2)));
25047   }
25048 
25049   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
25050   // are available or VBLENDV if AVX is available.
25051   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
25052   if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
25053       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
25054     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
25055     bool IsAlwaysSignaling;
25056     unsigned SSECC =
25057         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
25058                            CondOp0, CondOp1, IsAlwaysSignaling);
25059 
25060     if (Subtarget.hasAVX512()) {
25061       SDValue Cmp =
25062           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
25063                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
25064       assert(!VT.isVector() && "Not a scalar type?");
25065       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
25066     }
25067 
25068     if (SSECC < 8 || Subtarget.hasAVX()) {
25069       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
25070                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
25071 
25072       // If we have AVX, we can use a variable vector select (VBLENDV) instead
25073       // of 3 logic instructions for size savings and potentially speed.
25074       // Unfortunately, there is no scalar form of VBLENDV.
25075 
25076       // If either operand is a +0.0 constant, don't try this. We can expect to
25077       // optimize away at least one of the logic instructions later in that
25078       // case, so that sequence would be faster than a variable blend.
25079 
25080       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
25081       // uses XMM0 as the selection register. That may need just as many
25082       // instructions as the AND/ANDN/OR sequence due to register moves, so
25083       // don't bother.
25084       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
25085           !isNullFPConstant(Op2)) {
25086         // Convert to vectors, do a VSELECT, and convert back to scalar.
25087         // All of the conversions should be optimized away.
25088         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
25089         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
25090         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
25091         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
25092 
25093         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
25094         VCmp = DAG.getBitcast(VCmpVT, VCmp);
25095 
25096         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
25097 
25098         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
25099                            VSel, DAG.getIntPtrConstant(0, DL));
25100       }
25101       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
25102       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
25103       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
25104     }
25105   }
25106 
25107   // AVX512 fallback is to lower selects of scalar floats to masked moves.
25108   if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
25109     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
25110     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
25111   }
25112 
25113   if (Cond.getOpcode() == ISD::SETCC &&
25114       !isSoftFP16(Cond.getOperand(0).getSimpleValueType())) {
25115     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
25116       Cond = NewCond;
25117       // If the condition was updated, it's possible that the operands of the
25118       // select were also updated (for example, EmitTest has a RAUW). Refresh
25119       // the local references to the select operands in case they got stale.
25120       Op1 = Op.getOperand(1);
25121       Op2 = Op.getOperand(2);
25122     }
25123   }
25124 
25125   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
25126   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
25127   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
25128   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
25129   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
25130   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
25131   // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
25132   // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
25133   if (Cond.getOpcode() == X86ISD::SETCC &&
25134       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
25135       isNullConstant(Cond.getOperand(1).getOperand(1))) {
25136     SDValue Cmp = Cond.getOperand(1);
25137     SDValue CmpOp0 = Cmp.getOperand(0);
25138     unsigned CondCode = Cond.getConstantOperandVal(0);
25139 
25140     // Special handling for __builtin_ffs(X) - 1 pattern which looks like
25141     // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
25142     // handle to keep the CMP with 0. This should be removed by
25143     // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
25144     // cttz_zero_undef.
25145     auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
25146       return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
25147               Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
25148     };
25149     if (Subtarget.canUseCMOV() && (VT == MVT::i32 || VT == MVT::i64) &&
25150         ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
25151          (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
25152       // Keep Cmp.
25153     } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
25154         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
25155       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
25156       SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
25157 
25158       // 'X - 1' sets the carry flag if X == 0.
25159       // '0 - X' sets the carry flag if X != 0.
25160       // Convert the carry flag to a -1/0 mask with sbb:
25161       // select (X != 0), -1, Y --> 0 - X; or (sbb), Y
25162       // select (X == 0), Y, -1 --> 0 - X; or (sbb), Y
25163       // select (X != 0), Y, -1 --> X - 1; or (sbb), Y
25164       // select (X == 0), -1, Y --> X - 1; or (sbb), Y
25165       SDValue Sub;
25166       if (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE)) {
25167         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
25168         Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
25169       } else {
25170         SDValue One = DAG.getConstant(1, DL, CmpOp0.getValueType());
25171         Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, CmpOp0, One);
25172       }
25173       SDValue SBB = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25174                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
25175                                 Sub.getValue(1));
25176       return DAG.getNode(ISD::OR, DL, VT, SBB, Y);
25177     } else if (!Subtarget.canUseCMOV() && CondCode == X86::COND_E &&
25178                Cmp.getOperand(0).getOpcode() == ISD::AND &&
25179                isOneConstant(Cmp.getOperand(0).getOperand(1))) {
25180       SDValue Src1, Src2;
25181       // true if Op2 is XOR or OR operator and one of its operands
25182       // is equal to Op1
25183       // ( a , a op b) || ( b , a op b)
25184       auto isOrXorPattern = [&]() {
25185         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
25186             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
25187           Src1 =
25188               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
25189           Src2 = Op1;
25190           return true;
25191         }
25192         return false;
25193       };
25194 
25195       if (isOrXorPattern()) {
25196         SDValue Neg;
25197         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
25198         // we need mask of all zeros or ones with same size of the other
25199         // operands.
25200         if (CmpSz > VT.getSizeInBits())
25201           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
25202         else if (CmpSz < VT.getSizeInBits())
25203           Neg = DAG.getNode(ISD::AND, DL, VT,
25204               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
25205               DAG.getConstant(1, DL, VT));
25206         else
25207           Neg = CmpOp0;
25208         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
25209                                    Neg); // -(and (x, 0x1))
25210         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
25211         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
25212       }
25213     } else if ((VT == MVT::i32 || VT == MVT::i64) && isNullConstant(Op2) &&
25214                Cmp.getNode()->hasOneUse() && (CmpOp0 == Op1) &&
25215                ((CondCode == X86::COND_S) ||                    // smin(x, 0)
25216                 (CondCode == X86::COND_G && hasAndNot(Op1)))) { // smax(x, 0)
25217       // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
25218       //
25219       // If the comparison is testing for a positive value, we have to invert
25220       // the sign bit mask, so only do that transform if the target has a
25221       // bitwise 'and not' instruction (the invert is free).
25222       // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
25223       unsigned ShCt = VT.getSizeInBits() - 1;
25224       SDValue ShiftAmt = DAG.getConstant(ShCt, DL, VT);
25225       SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, Op1, ShiftAmt);
25226       if (CondCode == X86::COND_G)
25227         Shift = DAG.getNOT(DL, Shift, VT);
25228       return DAG.getNode(ISD::AND, DL, VT, Shift, Op1);
25229     }
25230   }
25231 
25232   // Look past (and (setcc_carry (cmp ...)), 1).
25233   if (Cond.getOpcode() == ISD::AND &&
25234       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
25235       isOneConstant(Cond.getOperand(1)))
25236     Cond = Cond.getOperand(0);
25237 
25238   // If condition flag is set by a X86ISD::CMP, then use it as the condition
25239   // setting operand in place of the X86ISD::SETCC.
25240   unsigned CondOpcode = Cond.getOpcode();
25241   if (CondOpcode == X86ISD::SETCC ||
25242       CondOpcode == X86ISD::SETCC_CARRY) {
25243     CC = Cond.getOperand(0);
25244 
25245     SDValue Cmp = Cond.getOperand(1);
25246     bool IllegalFPCMov = false;
25247     if (VT.isFloatingPoint() && !VT.isVector() &&
25248         !isScalarFPTypeInSSEReg(VT) && Subtarget.canUseCMOV())  // FPStack?
25249       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
25250 
25251     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
25252         Cmp.getOpcode() == X86ISD::BT) { // FIXME
25253       Cond = Cmp;
25254       AddTest = false;
25255     }
25256   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
25257              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
25258              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
25259     SDValue Value;
25260     X86::CondCode X86Cond;
25261     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
25262 
25263     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
25264     AddTest = false;
25265   }
25266 
25267   if (AddTest) {
25268     // Look past the truncate if the high bits are known zero.
25269     if (isTruncWithZeroHighBitsInput(Cond, DAG))
25270       Cond = Cond.getOperand(0);
25271 
25272     // We know the result of AND is compared against zero. Try to match
25273     // it to BT.
25274     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
25275       X86::CondCode X86CondCode;
25276       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, X86CondCode)) {
25277         CC = DAG.getTargetConstant(X86CondCode, DL, MVT::i8);
25278         Cond = BT;
25279         AddTest = false;
25280       }
25281     }
25282   }
25283 
25284   if (AddTest) {
25285     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
25286     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
25287   }
25288 
25289   // a <  b ? -1 :  0 -> RES = ~setcc_carry
25290   // a <  b ?  0 : -1 -> RES = setcc_carry
25291   // a >= b ? -1 :  0 -> RES = setcc_carry
25292   // a >= b ?  0 : -1 -> RES = ~setcc_carry
25293   if (Cond.getOpcode() == X86ISD::SUB) {
25294     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
25295 
25296     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
25297         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
25298         (isNullConstant(Op1) || isNullConstant(Op2))) {
25299       SDValue Res =
25300           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
25301                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
25302       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
25303         return DAG.getNOT(DL, Res, Res.getValueType());
25304       return Res;
25305     }
25306   }
25307 
25308   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
25309   // widen the cmov and push the truncate through. This avoids introducing a new
25310   // branch during isel and doesn't add any extensions.
25311   if (Op.getValueType() == MVT::i8 &&
25312       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
25313     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
25314     if (T1.getValueType() == T2.getValueType() &&
25315         // Exclude CopyFromReg to avoid partial register stalls.
25316         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
25317       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
25318                                  CC, Cond);
25319       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
25320     }
25321   }
25322 
25323   // Or finally, promote i8 cmovs if we have CMOV,
25324   //                 or i16 cmovs if it won't prevent folding a load.
25325   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
25326   //        legal, but EmitLoweredSelect() can not deal with these extensions
25327   //        being inserted between two CMOV's. (in i16 case too TBN)
25328   //        https://bugs.llvm.org/show_bug.cgi?id=40974
25329   if ((Op.getValueType() == MVT::i8 && Subtarget.canUseCMOV()) ||
25330       (Op.getValueType() == MVT::i16 && !X86::mayFoldLoad(Op1, Subtarget) &&
25331        !X86::mayFoldLoad(Op2, Subtarget))) {
25332     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
25333     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
25334     SDValue Ops[] = { Op2, Op1, CC, Cond };
25335     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
25336     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
25337   }
25338 
25339   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
25340   // condition is true.
25341   SDValue Ops[] = { Op2, Op1, CC, Cond };
25342   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
25343 }
25344 
25345 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
25346                                      const X86Subtarget &Subtarget,
25347                                      SelectionDAG &DAG) {
25348   MVT VT = Op->getSimpleValueType(0);
25349   SDValue In = Op->getOperand(0);
25350   MVT InVT = In.getSimpleValueType();
25351   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
25352   MVT VTElt = VT.getVectorElementType();
25353   SDLoc dl(Op);
25354 
25355   unsigned NumElts = VT.getVectorNumElements();
25356 
25357   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
25358   MVT ExtVT = VT;
25359   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
25360     // If v16i32 is to be avoided, we'll need to split and concatenate.
25361     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
25362       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
25363 
25364     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
25365   }
25366 
25367   // Widen to 512-bits if VLX is not supported.
25368   MVT WideVT = ExtVT;
25369   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
25370     NumElts *= 512 / ExtVT.getSizeInBits();
25371     InVT = MVT::getVectorVT(MVT::i1, NumElts);
25372     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
25373                      In, DAG.getIntPtrConstant(0, dl));
25374     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
25375   }
25376 
25377   SDValue V;
25378   MVT WideEltVT = WideVT.getVectorElementType();
25379   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
25380       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
25381     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
25382   } else {
25383     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
25384     SDValue Zero = DAG.getConstant(0, dl, WideVT);
25385     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
25386   }
25387 
25388   // Truncate if we had to extend i16/i8 above.
25389   if (VT != ExtVT) {
25390     WideVT = MVT::getVectorVT(VTElt, NumElts);
25391     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
25392   }
25393 
25394   // Extract back to 128/256-bit if we widened.
25395   if (WideVT != VT)
25396     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
25397                     DAG.getIntPtrConstant(0, dl));
25398 
25399   return V;
25400 }
25401 
25402 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
25403                                SelectionDAG &DAG) {
25404   SDValue In = Op->getOperand(0);
25405   MVT InVT = In.getSimpleValueType();
25406 
25407   if (InVT.getVectorElementType() == MVT::i1)
25408     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
25409 
25410   assert(Subtarget.hasAVX() && "Expected AVX support");
25411   return LowerAVXExtend(Op, DAG, Subtarget);
25412 }
25413 
25414 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
25415 // For sign extend this needs to handle all vector sizes and SSE4.1 and
25416 // non-SSE4.1 targets. For zero extend this should only handle inputs of
25417 // MVT::v64i8 when BWI is not supported, but AVX512 is.
25418 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
25419                                         const X86Subtarget &Subtarget,
25420                                         SelectionDAG &DAG) {
25421   SDValue In = Op->getOperand(0);
25422   MVT VT = Op->getSimpleValueType(0);
25423   MVT InVT = In.getSimpleValueType();
25424 
25425   MVT SVT = VT.getVectorElementType();
25426   MVT InSVT = InVT.getVectorElementType();
25427   assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits());
25428 
25429   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
25430     return SDValue();
25431   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
25432     return SDValue();
25433   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
25434       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
25435       !(VT.is512BitVector() && Subtarget.hasAVX512()))
25436     return SDValue();
25437 
25438   SDLoc dl(Op);
25439   unsigned Opc = Op.getOpcode();
25440   unsigned NumElts = VT.getVectorNumElements();
25441 
25442   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
25443   // For 512-bit vectors, we need 128-bits or 256-bits.
25444   if (InVT.getSizeInBits() > 128) {
25445     // Input needs to be at least the same number of elements as output, and
25446     // at least 128-bits.
25447     int InSize = InSVT.getSizeInBits() * NumElts;
25448     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
25449     InVT = In.getSimpleValueType();
25450   }
25451 
25452   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
25453   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
25454   // need to be handled here for 256/512-bit results.
25455   if (Subtarget.hasInt256()) {
25456     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
25457 
25458     if (InVT.getVectorNumElements() != NumElts)
25459       return DAG.getNode(Op.getOpcode(), dl, VT, In);
25460 
25461     // FIXME: Apparently we create inreg operations that could be regular
25462     // extends.
25463     unsigned ExtOpc =
25464         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
25465                                              : ISD::ZERO_EXTEND;
25466     return DAG.getNode(ExtOpc, dl, VT, In);
25467   }
25468 
25469   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
25470   if (Subtarget.hasAVX()) {
25471     assert(VT.is256BitVector() && "256-bit vector expected");
25472     MVT HalfVT = VT.getHalfNumVectorElementsVT();
25473     int HalfNumElts = HalfVT.getVectorNumElements();
25474 
25475     unsigned NumSrcElts = InVT.getVectorNumElements();
25476     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
25477     for (int i = 0; i != HalfNumElts; ++i)
25478       HiMask[i] = HalfNumElts + i;
25479 
25480     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
25481     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
25482     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
25483     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
25484   }
25485 
25486   // We should only get here for sign extend.
25487   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
25488   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
25489 
25490   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
25491   SDValue Curr = In;
25492   SDValue SignExt = Curr;
25493 
25494   // As SRAI is only available on i16/i32 types, we expand only up to i32
25495   // and handle i64 separately.
25496   if (InVT != MVT::v4i32) {
25497     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
25498 
25499     unsigned DestWidth = DestVT.getScalarSizeInBits();
25500     unsigned Scale = DestWidth / InSVT.getSizeInBits();
25501 
25502     unsigned InNumElts = InVT.getVectorNumElements();
25503     unsigned DestElts = DestVT.getVectorNumElements();
25504 
25505     // Build a shuffle mask that takes each input element and places it in the
25506     // MSBs of the new element size.
25507     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
25508     for (unsigned i = 0; i != DestElts; ++i)
25509       Mask[i * Scale + (Scale - 1)] = i;
25510 
25511     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
25512     Curr = DAG.getBitcast(DestVT, Curr);
25513 
25514     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
25515     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
25516                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
25517   }
25518 
25519   if (VT == MVT::v2i64) {
25520     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
25521     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
25522     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
25523     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
25524     SignExt = DAG.getBitcast(VT, SignExt);
25525   }
25526 
25527   return SignExt;
25528 }
25529 
25530 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
25531                                 SelectionDAG &DAG) {
25532   MVT VT = Op->getSimpleValueType(0);
25533   SDValue In = Op->getOperand(0);
25534   MVT InVT = In.getSimpleValueType();
25535   SDLoc dl(Op);
25536 
25537   if (InVT.getVectorElementType() == MVT::i1)
25538     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
25539 
25540   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
25541   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
25542          "Expected same number of elements");
25543   assert((VT.getVectorElementType() == MVT::i16 ||
25544           VT.getVectorElementType() == MVT::i32 ||
25545           VT.getVectorElementType() == MVT::i64) &&
25546          "Unexpected element type");
25547   assert((InVT.getVectorElementType() == MVT::i8 ||
25548           InVT.getVectorElementType() == MVT::i16 ||
25549           InVT.getVectorElementType() == MVT::i32) &&
25550          "Unexpected element type");
25551 
25552   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
25553     assert(InVT == MVT::v32i8 && "Unexpected VT!");
25554     return splitVectorIntUnary(Op, DAG);
25555   }
25556 
25557   if (Subtarget.hasInt256())
25558     return Op;
25559 
25560   // Optimize vectors in AVX mode
25561   // Sign extend  v8i16 to v8i32 and
25562   //              v4i32 to v4i64
25563   //
25564   // Divide input vector into two parts
25565   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
25566   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
25567   // concat the vectors to original VT
25568   MVT HalfVT = VT.getHalfNumVectorElementsVT();
25569   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
25570 
25571   unsigned NumElems = InVT.getVectorNumElements();
25572   SmallVector<int,8> ShufMask(NumElems, -1);
25573   for (unsigned i = 0; i != NumElems/2; ++i)
25574     ShufMask[i] = i + NumElems/2;
25575 
25576   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
25577   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
25578 
25579   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
25580 }
25581 
25582 /// Change a vector store into a pair of half-size vector stores.
25583 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
25584   SDValue StoredVal = Store->getValue();
25585   assert((StoredVal.getValueType().is256BitVector() ||
25586           StoredVal.getValueType().is512BitVector()) &&
25587          "Expecting 256/512-bit op");
25588 
25589   // Splitting volatile memory ops is not allowed unless the operation was not
25590   // legal to begin with. Assume the input store is legal (this transform is
25591   // only used for targets with AVX). Note: It is possible that we have an
25592   // illegal type like v2i128, and so we could allow splitting a volatile store
25593   // in that case if that is important.
25594   if (!Store->isSimple())
25595     return SDValue();
25596 
25597   SDLoc DL(Store);
25598   SDValue Value0, Value1;
25599   std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
25600   unsigned HalfOffset = Value0.getValueType().getStoreSize();
25601   SDValue Ptr0 = Store->getBasePtr();
25602   SDValue Ptr1 =
25603       DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(HalfOffset), DL);
25604   SDValue Ch0 =
25605       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
25606                    Store->getOriginalAlign(),
25607                    Store->getMemOperand()->getFlags());
25608   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
25609                              Store->getPointerInfo().getWithOffset(HalfOffset),
25610                              Store->getOriginalAlign(),
25611                              Store->getMemOperand()->getFlags());
25612   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
25613 }
25614 
25615 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
25616 /// type.
25617 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
25618                                     SelectionDAG &DAG) {
25619   SDValue StoredVal = Store->getValue();
25620   assert(StoreVT.is128BitVector() &&
25621          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
25622   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
25623 
25624   // Splitting volatile memory ops is not allowed unless the operation was not
25625   // legal to begin with. We are assuming the input op is legal (this transform
25626   // is only used for targets with AVX).
25627   if (!Store->isSimple())
25628     return SDValue();
25629 
25630   MVT StoreSVT = StoreVT.getScalarType();
25631   unsigned NumElems = StoreVT.getVectorNumElements();
25632   unsigned ScalarSize = StoreSVT.getStoreSize();
25633 
25634   SDLoc DL(Store);
25635   SmallVector<SDValue, 4> Stores;
25636   for (unsigned i = 0; i != NumElems; ++i) {
25637     unsigned Offset = i * ScalarSize;
25638     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(),
25639                                            TypeSize::Fixed(Offset), DL);
25640     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
25641                               DAG.getIntPtrConstant(i, DL));
25642     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
25643                               Store->getPointerInfo().getWithOffset(Offset),
25644                               Store->getOriginalAlign(),
25645                               Store->getMemOperand()->getFlags());
25646     Stores.push_back(Ch);
25647   }
25648   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
25649 }
25650 
25651 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
25652                           SelectionDAG &DAG) {
25653   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
25654   SDLoc dl(St);
25655   SDValue StoredVal = St->getValue();
25656 
25657   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
25658   if (StoredVal.getValueType().isVector() &&
25659       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
25660     unsigned NumElts = StoredVal.getValueType().getVectorNumElements();
25661     assert(NumElts <= 8 && "Unexpected VT");
25662     assert(!St->isTruncatingStore() && "Expected non-truncating store");
25663     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
25664            "Expected AVX512F without AVX512DQI");
25665 
25666     // We must pad with zeros to ensure we store zeroes to any unused bits.
25667     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
25668                             DAG.getUNDEF(MVT::v16i1), StoredVal,
25669                             DAG.getIntPtrConstant(0, dl));
25670     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
25671     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
25672     // Make sure we store zeros in the extra bits.
25673     if (NumElts < 8)
25674       StoredVal = DAG.getZeroExtendInReg(
25675           StoredVal, dl, EVT::getIntegerVT(*DAG.getContext(), NumElts));
25676 
25677     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
25678                         St->getPointerInfo(), St->getOriginalAlign(),
25679                         St->getMemOperand()->getFlags());
25680   }
25681 
25682   if (St->isTruncatingStore())
25683     return SDValue();
25684 
25685   // If this is a 256-bit store of concatenated ops, we are better off splitting
25686   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
25687   // and each half can execute independently. Some cores would split the op into
25688   // halves anyway, so the concat (vinsertf128) is purely an extra op.
25689   MVT StoreVT = StoredVal.getSimpleValueType();
25690   if (StoreVT.is256BitVector() ||
25691       ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
25692        !Subtarget.hasBWI())) {
25693     SmallVector<SDValue, 4> CatOps;
25694     if (StoredVal.hasOneUse() &&
25695         collectConcatOps(StoredVal.getNode(), CatOps, DAG))
25696       return splitVectorStore(St, DAG);
25697     return SDValue();
25698   }
25699 
25700   if (StoreVT.is32BitVector())
25701     return SDValue();
25702 
25703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25704   assert(StoreVT.is64BitVector() && "Unexpected VT");
25705   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
25706              TargetLowering::TypeWidenVector &&
25707          "Unexpected type action!");
25708 
25709   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
25710   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
25711                           DAG.getUNDEF(StoreVT));
25712 
25713   if (Subtarget.hasSSE2()) {
25714     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
25715     // and store it.
25716     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
25717     MVT CastVT = MVT::getVectorVT(StVT, 2);
25718     StoredVal = DAG.getBitcast(CastVT, StoredVal);
25719     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
25720                             DAG.getIntPtrConstant(0, dl));
25721 
25722     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
25723                         St->getPointerInfo(), St->getOriginalAlign(),
25724                         St->getMemOperand()->getFlags());
25725   }
25726   assert(Subtarget.hasSSE1() && "Expected SSE");
25727   SDVTList Tys = DAG.getVTList(MVT::Other);
25728   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
25729   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
25730                                  St->getMemOperand());
25731 }
25732 
25733 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
25734 // may emit an illegal shuffle but the expansion is still better than scalar
25735 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
25736 // we'll emit a shuffle and a arithmetic shift.
25737 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
25738 // TODO: It is possible to support ZExt by zeroing the undef values during
25739 // the shuffle phase or after the shuffle.
25740 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
25741                                  SelectionDAG &DAG) {
25742   MVT RegVT = Op.getSimpleValueType();
25743   assert(RegVT.isVector() && "We only custom lower vector loads.");
25744   assert(RegVT.isInteger() &&
25745          "We only custom lower integer vector loads.");
25746 
25747   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
25748   SDLoc dl(Ld);
25749 
25750   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
25751   if (RegVT.getVectorElementType() == MVT::i1) {
25752     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
25753     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
25754     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
25755            "Expected AVX512F without AVX512DQI");
25756 
25757     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
25758                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
25759                                 Ld->getMemOperand()->getFlags());
25760 
25761     // Replace chain users with the new chain.
25762     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
25763 
25764     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
25765     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
25766                       DAG.getBitcast(MVT::v16i1, Val),
25767                       DAG.getIntPtrConstant(0, dl));
25768     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
25769   }
25770 
25771   return SDValue();
25772 }
25773 
25774 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
25775 /// each of which has no other use apart from the AND / OR.
25776 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
25777   Opc = Op.getOpcode();
25778   if (Opc != ISD::OR && Opc != ISD::AND)
25779     return false;
25780   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
25781           Op.getOperand(0).hasOneUse() &&
25782           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
25783           Op.getOperand(1).hasOneUse());
25784 }
25785 
25786 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
25787   SDValue Chain = Op.getOperand(0);
25788   SDValue Cond  = Op.getOperand(1);
25789   SDValue Dest  = Op.getOperand(2);
25790   SDLoc dl(Op);
25791 
25792   // Bail out when we don't have native compare instructions.
25793   if (Cond.getOpcode() == ISD::SETCC &&
25794       Cond.getOperand(0).getValueType() != MVT::f128 &&
25795       !isSoftFP16(Cond.getOperand(0).getValueType())) {
25796     SDValue LHS = Cond.getOperand(0);
25797     SDValue RHS = Cond.getOperand(1);
25798     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
25799 
25800     // Special case for
25801     // setcc([su]{add,sub,mul}o == 0)
25802     // setcc([su]{add,sub,mul}o != 1)
25803     if (ISD::isOverflowIntrOpRes(LHS) &&
25804         (CC == ISD::SETEQ || CC == ISD::SETNE) &&
25805         (isNullConstant(RHS) || isOneConstant(RHS))) {
25806       SDValue Value, Overflow;
25807       X86::CondCode X86Cond;
25808       std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
25809 
25810       if ((CC == ISD::SETEQ) == isNullConstant(RHS))
25811         X86Cond = X86::GetOppositeBranchCondition(X86Cond);
25812 
25813       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25814       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25815                          Overflow);
25816     }
25817 
25818     if (LHS.getSimpleValueType().isInteger()) {
25819       SDValue CCVal;
25820       SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
25821       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25822                          EFLAGS);
25823     }
25824 
25825     if (CC == ISD::SETOEQ) {
25826       // For FCMP_OEQ, we can emit
25827       // two branches instead of an explicit AND instruction with a
25828       // separate test. However, we only do this if this block doesn't
25829       // have a fall-through edge, because this requires an explicit
25830       // jmp when the condition is false.
25831       if (Op.getNode()->hasOneUse()) {
25832         SDNode *User = *Op.getNode()->use_begin();
25833         // Look for an unconditional branch following this conditional branch.
25834         // We need this because we need to reverse the successors in order
25835         // to implement FCMP_OEQ.
25836         if (User->getOpcode() == ISD::BR) {
25837           SDValue FalseBB = User->getOperand(1);
25838           SDNode *NewBR =
25839             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
25840           assert(NewBR == User);
25841           (void)NewBR;
25842           Dest = FalseBB;
25843 
25844           SDValue Cmp =
25845               DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25846           SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
25847           Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
25848                               CCVal, Cmp);
25849           CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
25850           return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25851                              Cmp);
25852         }
25853       }
25854     } else if (CC == ISD::SETUNE) {
25855       // For FCMP_UNE, we can emit
25856       // two branches instead of an explicit OR instruction with a
25857       // separate test.
25858       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25859       SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
25860       Chain =
25861           DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
25862       CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
25863       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25864                          Cmp);
25865     } else {
25866       X86::CondCode X86Cond =
25867           TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
25868       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25869       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25870       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25871                          Cmp);
25872     }
25873   }
25874 
25875   if (ISD::isOverflowIntrOpRes(Cond)) {
25876     SDValue Value, Overflow;
25877     X86::CondCode X86Cond;
25878     std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
25879 
25880     SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25881     return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25882                        Overflow);
25883   }
25884 
25885   // Look past the truncate if the high bits are known zero.
25886   if (isTruncWithZeroHighBitsInput(Cond, DAG))
25887     Cond = Cond.getOperand(0);
25888 
25889   EVT CondVT = Cond.getValueType();
25890 
25891   // Add an AND with 1 if we don't already have one.
25892   if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
25893     Cond =
25894         DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
25895 
25896   SDValue LHS = Cond;
25897   SDValue RHS = DAG.getConstant(0, dl, CondVT);
25898 
25899   SDValue CCVal;
25900   SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
25901   return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25902                      EFLAGS);
25903 }
25904 
25905 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
25906 // Calls to _alloca are needed to probe the stack when allocating more than 4k
25907 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
25908 // that the guard pages used by the OS virtual memory manager are allocated in
25909 // correct sequence.
25910 SDValue
25911 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
25912                                            SelectionDAG &DAG) const {
25913   MachineFunction &MF = DAG.getMachineFunction();
25914   bool SplitStack = MF.shouldSplitStack();
25915   bool EmitStackProbeCall = hasStackProbeSymbol(MF);
25916   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
25917                SplitStack || EmitStackProbeCall;
25918   SDLoc dl(Op);
25919 
25920   // Get the inputs.
25921   SDNode *Node = Op.getNode();
25922   SDValue Chain = Op.getOperand(0);
25923   SDValue Size  = Op.getOperand(1);
25924   MaybeAlign Alignment(Op.getConstantOperandVal(2));
25925   EVT VT = Node->getValueType(0);
25926 
25927   // Chain the dynamic stack allocation so that it doesn't modify the stack
25928   // pointer when other instructions are using the stack.
25929   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
25930 
25931   bool Is64Bit = Subtarget.is64Bit();
25932   MVT SPTy = getPointerTy(DAG.getDataLayout());
25933 
25934   SDValue Result;
25935   if (!Lower) {
25936     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25937     Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
25938     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
25939                     " not tell us which reg is the stack pointer!");
25940 
25941     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
25942     const Align StackAlign = TFI.getStackAlign();
25943     if (hasInlineStackProbe(MF)) {
25944       MachineRegisterInfo &MRI = MF.getRegInfo();
25945 
25946       const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
25947       Register Vreg = MRI.createVirtualRegister(AddrRegClass);
25948       Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
25949       Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
25950                            DAG.getRegister(Vreg, SPTy));
25951     } else {
25952       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
25953       Chain = SP.getValue(1);
25954       Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
25955     }
25956     if (Alignment && *Alignment > StackAlign)
25957       Result =
25958           DAG.getNode(ISD::AND, dl, VT, Result,
25959                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
25960     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
25961   } else if (SplitStack) {
25962     MachineRegisterInfo &MRI = MF.getRegInfo();
25963 
25964     if (Is64Bit) {
25965       // The 64 bit implementation of segmented stacks needs to clobber both r10
25966       // r11. This makes it impossible to use it along with nested parameters.
25967       const Function &F = MF.getFunction();
25968       for (const auto &A : F.args()) {
25969         if (A.hasNestAttr())
25970           report_fatal_error("Cannot use segmented stacks with functions that "
25971                              "have nested arguments.");
25972       }
25973     }
25974 
25975     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
25976     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
25977     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
25978     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
25979                                 DAG.getRegister(Vreg, SPTy));
25980   } else {
25981     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
25982     Chain = DAG.getNode(X86ISD::DYN_ALLOCA, dl, NodeTys, Chain, Size);
25983     MF.getInfo<X86MachineFunctionInfo>()->setHasDynAlloca(true);
25984 
25985     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25986     Register SPReg = RegInfo->getStackRegister();
25987     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
25988     Chain = SP.getValue(1);
25989 
25990     if (Alignment) {
25991       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
25992                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
25993       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
25994     }
25995 
25996     Result = SP;
25997   }
25998 
25999   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
26000                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
26001 
26002   SDValue Ops[2] = {Result, Chain};
26003   return DAG.getMergeValues(Ops, dl);
26004 }
26005 
26006 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
26007   MachineFunction &MF = DAG.getMachineFunction();
26008   auto PtrVT = getPointerTy(MF.getDataLayout());
26009   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
26010 
26011   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
26012   SDLoc DL(Op);
26013 
26014   if (!Subtarget.is64Bit() ||
26015       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
26016     // vastart just stores the address of the VarArgsFrameIndex slot into the
26017     // memory location argument.
26018     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
26019     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
26020                         MachinePointerInfo(SV));
26021   }
26022 
26023   // __va_list_tag:
26024   //   gp_offset         (0 - 6 * 8)
26025   //   fp_offset         (48 - 48 + 8 * 16)
26026   //   overflow_arg_area (point to parameters coming in memory).
26027   //   reg_save_area
26028   SmallVector<SDValue, 8> MemOps;
26029   SDValue FIN = Op.getOperand(1);
26030   // Store gp_offset
26031   SDValue Store = DAG.getStore(
26032       Op.getOperand(0), DL,
26033       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
26034       MachinePointerInfo(SV));
26035   MemOps.push_back(Store);
26036 
26037   // Store fp_offset
26038   FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::Fixed(4), DL);
26039   Store = DAG.getStore(
26040       Op.getOperand(0), DL,
26041       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
26042       MachinePointerInfo(SV, 4));
26043   MemOps.push_back(Store);
26044 
26045   // Store ptr to overflow_arg_area
26046   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
26047   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
26048   Store =
26049       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
26050   MemOps.push_back(Store);
26051 
26052   // Store ptr to reg_save_area.
26053   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
26054       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
26055   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
26056   Store = DAG.getStore(
26057       Op.getOperand(0), DL, RSFIN, FIN,
26058       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
26059   MemOps.push_back(Store);
26060   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
26061 }
26062 
26063 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
26064   assert(Subtarget.is64Bit() &&
26065          "LowerVAARG only handles 64-bit va_arg!");
26066   assert(Op.getNumOperands() == 4);
26067 
26068   MachineFunction &MF = DAG.getMachineFunction();
26069   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
26070     // The Win64 ABI uses char* instead of a structure.
26071     return DAG.expandVAArg(Op.getNode());
26072 
26073   SDValue Chain = Op.getOperand(0);
26074   SDValue SrcPtr = Op.getOperand(1);
26075   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
26076   unsigned Align = Op.getConstantOperandVal(3);
26077   SDLoc dl(Op);
26078 
26079   EVT ArgVT = Op.getNode()->getValueType(0);
26080   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
26081   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
26082   uint8_t ArgMode;
26083 
26084   // Decide which area this value should be read from.
26085   // TODO: Implement the AMD64 ABI in its entirety. This simple
26086   // selection mechanism works only for the basic types.
26087   assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
26088   if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
26089     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
26090   } else {
26091     assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
26092            "Unhandled argument type in LowerVAARG");
26093     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
26094   }
26095 
26096   if (ArgMode == 2) {
26097     // Make sure using fp_offset makes sense.
26098     assert(!Subtarget.useSoftFloat() &&
26099            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
26100            Subtarget.hasSSE1());
26101   }
26102 
26103   // Insert VAARG node into the DAG
26104   // VAARG returns two values: Variable Argument Address, Chain
26105   SDValue InstOps[] = {Chain, SrcPtr,
26106                        DAG.getTargetConstant(ArgSize, dl, MVT::i32),
26107                        DAG.getTargetConstant(ArgMode, dl, MVT::i8),
26108                        DAG.getTargetConstant(Align, dl, MVT::i32)};
26109   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
26110   SDValue VAARG = DAG.getMemIntrinsicNode(
26111       Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
26112       VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
26113       /*Alignment=*/None,
26114       MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
26115   Chain = VAARG.getValue(1);
26116 
26117   // Load the next argument and return it
26118   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
26119 }
26120 
26121 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
26122                            SelectionDAG &DAG) {
26123   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
26124   // where a va_list is still an i8*.
26125   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
26126   if (Subtarget.isCallingConvWin64(
26127         DAG.getMachineFunction().getFunction().getCallingConv()))
26128     // Probably a Win64 va_copy.
26129     return DAG.expandVACopy(Op.getNode());
26130 
26131   SDValue Chain = Op.getOperand(0);
26132   SDValue DstPtr = Op.getOperand(1);
26133   SDValue SrcPtr = Op.getOperand(2);
26134   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
26135   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
26136   SDLoc DL(Op);
26137 
26138   return DAG.getMemcpy(
26139       Chain, DL, DstPtr, SrcPtr,
26140       DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
26141       Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
26142       false, MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
26143 }
26144 
26145 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
26146 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
26147   switch (Opc) {
26148   case ISD::SHL:
26149   case X86ISD::VSHL:
26150   case X86ISD::VSHLI:
26151     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
26152   case ISD::SRL:
26153   case X86ISD::VSRL:
26154   case X86ISD::VSRLI:
26155     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
26156   case ISD::SRA:
26157   case X86ISD::VSRA:
26158   case X86ISD::VSRAI:
26159     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
26160   }
26161   llvm_unreachable("Unknown target vector shift node");
26162 }
26163 
26164 /// Handle vector element shifts where the shift amount is a constant.
26165 /// Takes immediate version of shift as input.
26166 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
26167                                           SDValue SrcOp, uint64_t ShiftAmt,
26168                                           SelectionDAG &DAG) {
26169   MVT ElementType = VT.getVectorElementType();
26170 
26171   // Bitcast the source vector to the output type, this is mainly necessary for
26172   // vXi8/vXi64 shifts.
26173   if (VT != SrcOp.getSimpleValueType())
26174     SrcOp = DAG.getBitcast(VT, SrcOp);
26175 
26176   // Fold this packed shift into its first operand if ShiftAmt is 0.
26177   if (ShiftAmt == 0)
26178     return SrcOp;
26179 
26180   // Check for ShiftAmt >= element width
26181   if (ShiftAmt >= ElementType.getSizeInBits()) {
26182     if (Opc == X86ISD::VSRAI)
26183       ShiftAmt = ElementType.getSizeInBits() - 1;
26184     else
26185       return DAG.getConstant(0, dl, VT);
26186   }
26187 
26188   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
26189          && "Unknown target vector shift-by-constant node");
26190 
26191   // Fold this packed vector shift into a build vector if SrcOp is a
26192   // vector of Constants or UNDEFs.
26193   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
26194     unsigned ShiftOpc;
26195     switch (Opc) {
26196     default: llvm_unreachable("Unknown opcode!");
26197     case X86ISD::VSHLI:
26198       ShiftOpc = ISD::SHL;
26199       break;
26200     case X86ISD::VSRLI:
26201       ShiftOpc = ISD::SRL;
26202       break;
26203     case X86ISD::VSRAI:
26204       ShiftOpc = ISD::SRA;
26205       break;
26206     }
26207 
26208     SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
26209     if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
26210       return C;
26211   }
26212 
26213   return DAG.getNode(Opc, dl, VT, SrcOp,
26214                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
26215 }
26216 
26217 /// Handle vector element shifts by a splat shift amount
26218 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
26219                                    SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
26220                                    const X86Subtarget &Subtarget,
26221                                    SelectionDAG &DAG) {
26222   MVT AmtVT = ShAmt.getSimpleValueType();
26223   assert(AmtVT.isVector() && "Vector shift type mismatch");
26224   assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
26225          "Illegal vector splat index");
26226 
26227   // Move the splat element to the bottom element.
26228   if (ShAmtIdx != 0) {
26229     SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
26230     Mask[0] = ShAmtIdx;
26231     ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
26232   }
26233 
26234   // Peek through any zext node if we can get back to a 128-bit source.
26235   if (AmtVT.getScalarSizeInBits() == 64 &&
26236       (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
26237        ShAmt.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
26238       ShAmt.getOperand(0).getValueType().isSimple() &&
26239       ShAmt.getOperand(0).getValueType().is128BitVector()) {
26240     ShAmt = ShAmt.getOperand(0);
26241     AmtVT = ShAmt.getSimpleValueType();
26242   }
26243 
26244   // See if we can mask off the upper elements using the existing source node.
26245   // The shift uses the entire lower 64-bits of the amount vector, so no need to
26246   // do this for vXi64 types.
26247   bool IsMasked = false;
26248   if (AmtVT.getScalarSizeInBits() < 64) {
26249     if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
26250         ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
26251       // If the shift amount has come from a scalar, then zero-extend the scalar
26252       // before moving to the vector.
26253       ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
26254       ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
26255       ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
26256       AmtVT = MVT::v4i32;
26257       IsMasked = true;
26258     } else if (ShAmt.getOpcode() == ISD::AND) {
26259       // See if the shift amount is already masked (e.g. for rotation modulo),
26260       // then we can zero-extend it by setting all the other mask elements to
26261       // zero.
26262       SmallVector<SDValue> MaskElts(
26263           AmtVT.getVectorNumElements(),
26264           DAG.getConstant(0, dl, AmtVT.getScalarType()));
26265       MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
26266       SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
26267       if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
26268                                              {ShAmt.getOperand(1), Mask}))) {
26269         ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
26270         IsMasked = true;
26271       }
26272     }
26273   }
26274 
26275   // Extract if the shift amount vector is larger than 128-bits.
26276   if (AmtVT.getSizeInBits() > 128) {
26277     ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
26278     AmtVT = ShAmt.getSimpleValueType();
26279   }
26280 
26281   // Zero-extend bottom element to v2i64 vector type, either by extension or
26282   // shuffle masking.
26283   if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
26284     if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
26285                                 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
26286       ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
26287     } else if (Subtarget.hasSSE41()) {
26288       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
26289                           MVT::v2i64, ShAmt);
26290     } else {
26291       SDValue ByteShift = DAG.getTargetConstant(
26292           (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
26293       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
26294       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
26295                           ByteShift);
26296       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
26297                           ByteShift);
26298     }
26299   }
26300 
26301   // Change opcode to non-immediate version.
26302   Opc = getTargetVShiftUniformOpcode(Opc, true);
26303 
26304   // The return type has to be a 128-bit type with the same element
26305   // type as the input type.
26306   MVT EltVT = VT.getVectorElementType();
26307   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
26308 
26309   ShAmt = DAG.getBitcast(ShVT, ShAmt);
26310   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
26311 }
26312 
26313 /// Return Mask with the necessary casting or extending
26314 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
26315 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
26316                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
26317                            const SDLoc &dl) {
26318 
26319   if (isAllOnesConstant(Mask))
26320     return DAG.getConstant(1, dl, MaskVT);
26321   if (X86::isZeroNode(Mask))
26322     return DAG.getConstant(0, dl, MaskVT);
26323 
26324   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
26325 
26326   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
26327     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
26328     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
26329     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
26330     SDValue Lo, Hi;
26331     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
26332                         DAG.getConstant(0, dl, MVT::i32));
26333     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
26334                         DAG.getConstant(1, dl, MVT::i32));
26335 
26336     Lo = DAG.getBitcast(MVT::v32i1, Lo);
26337     Hi = DAG.getBitcast(MVT::v32i1, Hi);
26338 
26339     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
26340   } else {
26341     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
26342                                      Mask.getSimpleValueType().getSizeInBits());
26343     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
26344     // are extracted by EXTRACT_SUBVECTOR.
26345     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
26346                        DAG.getBitcast(BitcastVT, Mask),
26347                        DAG.getIntPtrConstant(0, dl));
26348   }
26349 }
26350 
26351 /// Return (and \p Op, \p Mask) for compare instructions or
26352 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
26353 /// necessary casting or extending for \p Mask when lowering masking intrinsics
26354 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
26355                                     SDValue PreservedSrc,
26356                                     const X86Subtarget &Subtarget,
26357                                     SelectionDAG &DAG) {
26358   MVT VT = Op.getSimpleValueType();
26359   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
26360   unsigned OpcodeSelect = ISD::VSELECT;
26361   SDLoc dl(Op);
26362 
26363   if (isAllOnesConstant(Mask))
26364     return Op;
26365 
26366   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26367 
26368   if (PreservedSrc.isUndef())
26369     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
26370   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
26371 }
26372 
26373 /// Creates an SDNode for a predicated scalar operation.
26374 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
26375 /// The mask is coming as MVT::i8 and it should be transformed
26376 /// to MVT::v1i1 while lowering masking intrinsics.
26377 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
26378 /// "X86select" instead of "vselect". We just can't create the "vselect" node
26379 /// for a scalar instruction.
26380 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
26381                                     SDValue PreservedSrc,
26382                                     const X86Subtarget &Subtarget,
26383                                     SelectionDAG &DAG) {
26384 
26385   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
26386     if (MaskConst->getZExtValue() & 0x1)
26387       return Op;
26388 
26389   MVT VT = Op.getSimpleValueType();
26390   SDLoc dl(Op);
26391 
26392   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
26393   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
26394                               DAG.getBitcast(MVT::v8i1, Mask),
26395                               DAG.getIntPtrConstant(0, dl));
26396   if (Op.getOpcode() == X86ISD::FSETCCM ||
26397       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
26398       Op.getOpcode() == X86ISD::VFPCLASSS)
26399     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
26400 
26401   if (PreservedSrc.isUndef())
26402     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
26403   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
26404 }
26405 
26406 static int getSEHRegistrationNodeSize(const Function *Fn) {
26407   if (!Fn->hasPersonalityFn())
26408     report_fatal_error(
26409         "querying registration node size for function without personality");
26410   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
26411   // WinEHStatePass for the full struct definition.
26412   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
26413   case EHPersonality::MSVC_X86SEH: return 24;
26414   case EHPersonality::MSVC_CXX: return 16;
26415   default: break;
26416   }
26417   report_fatal_error(
26418       "can only recover FP for 32-bit MSVC EH personality functions");
26419 }
26420 
26421 /// When the MSVC runtime transfers control to us, either to an outlined
26422 /// function or when returning to a parent frame after catching an exception, we
26423 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
26424 /// Here's the math:
26425 ///   RegNodeBase = EntryEBP - RegNodeSize
26426 ///   ParentFP = RegNodeBase - ParentFrameOffset
26427 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
26428 /// subtracting the offset (negative on x86) takes us back to the parent FP.
26429 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
26430                                    SDValue EntryEBP) {
26431   MachineFunction &MF = DAG.getMachineFunction();
26432   SDLoc dl;
26433 
26434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26435   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
26436 
26437   // It's possible that the parent function no longer has a personality function
26438   // if the exceptional code was optimized away, in which case we just return
26439   // the incoming EBP.
26440   if (!Fn->hasPersonalityFn())
26441     return EntryEBP;
26442 
26443   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
26444   // registration, or the .set_setframe offset.
26445   MCSymbol *OffsetSym =
26446       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
26447           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
26448   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
26449   SDValue ParentFrameOffset =
26450       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
26451 
26452   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
26453   // prologue to RBP in the parent function.
26454   const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
26455   if (Subtarget.is64Bit())
26456     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
26457 
26458   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
26459   // RegNodeBase = EntryEBP - RegNodeSize
26460   // ParentFP = RegNodeBase - ParentFrameOffset
26461   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
26462                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
26463   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
26464 }
26465 
26466 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
26467                                                    SelectionDAG &DAG) const {
26468   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
26469   auto isRoundModeCurDirection = [](SDValue Rnd) {
26470     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
26471       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
26472 
26473     return false;
26474   };
26475   auto isRoundModeSAE = [](SDValue Rnd) {
26476     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
26477       unsigned RC = C->getZExtValue();
26478       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
26479         // Clear the NO_EXC bit and check remaining bits.
26480         RC ^= X86::STATIC_ROUNDING::NO_EXC;
26481         // As a convenience we allow no other bits or explicitly
26482         // current direction.
26483         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
26484       }
26485     }
26486 
26487     return false;
26488   };
26489   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
26490     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
26491       RC = C->getZExtValue();
26492       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
26493         // Clear the NO_EXC bit and check remaining bits.
26494         RC ^= X86::STATIC_ROUNDING::NO_EXC;
26495         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
26496                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
26497                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
26498                RC == X86::STATIC_ROUNDING::TO_ZERO;
26499       }
26500     }
26501 
26502     return false;
26503   };
26504 
26505   SDLoc dl(Op);
26506   unsigned IntNo = Op.getConstantOperandVal(0);
26507   MVT VT = Op.getSimpleValueType();
26508   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
26509 
26510   // Propagate flags from original node to transformed node(s).
26511   SelectionDAG::FlagInserter FlagsInserter(DAG, Op->getFlags());
26512 
26513   if (IntrData) {
26514     switch(IntrData->Type) {
26515     case INTR_TYPE_1OP: {
26516       // We specify 2 possible opcodes for intrinsics with rounding modes.
26517       // First, we check if the intrinsic may have non-default rounding mode,
26518       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
26519       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26520       if (IntrWithRoundingModeOpcode != 0) {
26521         SDValue Rnd = Op.getOperand(2);
26522         unsigned RC = 0;
26523         if (isRoundModeSAEToX(Rnd, RC))
26524           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
26525                              Op.getOperand(1),
26526                              DAG.getTargetConstant(RC, dl, MVT::i32));
26527         if (!isRoundModeCurDirection(Rnd))
26528           return SDValue();
26529       }
26530       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26531                          Op.getOperand(1));
26532     }
26533     case INTR_TYPE_1OP_SAE: {
26534       SDValue Sae = Op.getOperand(2);
26535 
26536       unsigned Opc;
26537       if (isRoundModeCurDirection(Sae))
26538         Opc = IntrData->Opc0;
26539       else if (isRoundModeSAE(Sae))
26540         Opc = IntrData->Opc1;
26541       else
26542         return SDValue();
26543 
26544       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
26545     }
26546     case INTR_TYPE_2OP: {
26547       SDValue Src2 = Op.getOperand(2);
26548 
26549       // We specify 2 possible opcodes for intrinsics with rounding modes.
26550       // First, we check if the intrinsic may have non-default rounding mode,
26551       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
26552       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26553       if (IntrWithRoundingModeOpcode != 0) {
26554         SDValue Rnd = Op.getOperand(3);
26555         unsigned RC = 0;
26556         if (isRoundModeSAEToX(Rnd, RC))
26557           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
26558                              Op.getOperand(1), Src2,
26559                              DAG.getTargetConstant(RC, dl, MVT::i32));
26560         if (!isRoundModeCurDirection(Rnd))
26561           return SDValue();
26562       }
26563 
26564       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26565                          Op.getOperand(1), Src2);
26566     }
26567     case INTR_TYPE_2OP_SAE: {
26568       SDValue Sae = Op.getOperand(3);
26569 
26570       unsigned Opc;
26571       if (isRoundModeCurDirection(Sae))
26572         Opc = IntrData->Opc0;
26573       else if (isRoundModeSAE(Sae))
26574         Opc = IntrData->Opc1;
26575       else
26576         return SDValue();
26577 
26578       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
26579                          Op.getOperand(2));
26580     }
26581     case INTR_TYPE_3OP:
26582     case INTR_TYPE_3OP_IMM8: {
26583       SDValue Src1 = Op.getOperand(1);
26584       SDValue Src2 = Op.getOperand(2);
26585       SDValue Src3 = Op.getOperand(3);
26586 
26587       if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
26588           Src3.getValueType() != MVT::i8) {
26589         Src3 = DAG.getTargetConstant(
26590             cast<ConstantSDNode>(Src3)->getZExtValue() & 0xff, dl, MVT::i8);
26591       }
26592 
26593       // We specify 2 possible opcodes for intrinsics with rounding modes.
26594       // First, we check if the intrinsic may have non-default rounding mode,
26595       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
26596       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26597       if (IntrWithRoundingModeOpcode != 0) {
26598         SDValue Rnd = Op.getOperand(4);
26599         unsigned RC = 0;
26600         if (isRoundModeSAEToX(Rnd, RC))
26601           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
26602                              Src1, Src2, Src3,
26603                              DAG.getTargetConstant(RC, dl, MVT::i32));
26604         if (!isRoundModeCurDirection(Rnd))
26605           return SDValue();
26606       }
26607 
26608       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26609                          {Src1, Src2, Src3});
26610     }
26611     case INTR_TYPE_4OP_IMM8: {
26612       assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant);
26613       SDValue Src4 = Op.getOperand(4);
26614       if (Src4.getValueType() != MVT::i8) {
26615         Src4 = DAG.getTargetConstant(
26616             cast<ConstantSDNode>(Src4)->getZExtValue() & 0xff, dl, MVT::i8);
26617       }
26618 
26619       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26620                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
26621                          Src4);
26622     }
26623     case INTR_TYPE_1OP_MASK: {
26624       SDValue Src = Op.getOperand(1);
26625       SDValue PassThru = Op.getOperand(2);
26626       SDValue Mask = Op.getOperand(3);
26627       // We add rounding mode to the Node when
26628       //   - RC Opcode is specified and
26629       //   - RC is not "current direction".
26630       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26631       if (IntrWithRoundingModeOpcode != 0) {
26632         SDValue Rnd = Op.getOperand(4);
26633         unsigned RC = 0;
26634         if (isRoundModeSAEToX(Rnd, RC))
26635           return getVectorMaskingNode(
26636               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
26637                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
26638               Mask, PassThru, Subtarget, DAG);
26639         if (!isRoundModeCurDirection(Rnd))
26640           return SDValue();
26641       }
26642       return getVectorMaskingNode(
26643           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
26644           Subtarget, DAG);
26645     }
26646     case INTR_TYPE_1OP_MASK_SAE: {
26647       SDValue Src = Op.getOperand(1);
26648       SDValue PassThru = Op.getOperand(2);
26649       SDValue Mask = Op.getOperand(3);
26650       SDValue Rnd = Op.getOperand(4);
26651 
26652       unsigned Opc;
26653       if (isRoundModeCurDirection(Rnd))
26654         Opc = IntrData->Opc0;
26655       else if (isRoundModeSAE(Rnd))
26656         Opc = IntrData->Opc1;
26657       else
26658         return SDValue();
26659 
26660       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
26661                                   Subtarget, DAG);
26662     }
26663     case INTR_TYPE_SCALAR_MASK: {
26664       SDValue Src1 = Op.getOperand(1);
26665       SDValue Src2 = Op.getOperand(2);
26666       SDValue passThru = Op.getOperand(3);
26667       SDValue Mask = Op.getOperand(4);
26668       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26669       // There are 2 kinds of intrinsics in this group:
26670       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
26671       // (2) With rounding mode and sae - 7 operands.
26672       bool HasRounding = IntrWithRoundingModeOpcode != 0;
26673       if (Op.getNumOperands() == (5U + HasRounding)) {
26674         if (HasRounding) {
26675           SDValue Rnd = Op.getOperand(5);
26676           unsigned RC = 0;
26677           if (isRoundModeSAEToX(Rnd, RC))
26678             return getScalarMaskingNode(
26679                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
26680                             DAG.getTargetConstant(RC, dl, MVT::i32)),
26681                 Mask, passThru, Subtarget, DAG);
26682           if (!isRoundModeCurDirection(Rnd))
26683             return SDValue();
26684         }
26685         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
26686                                                 Src2),
26687                                     Mask, passThru, Subtarget, DAG);
26688       }
26689 
26690       assert(Op.getNumOperands() == (6U + HasRounding) &&
26691              "Unexpected intrinsic form");
26692       SDValue RoundingMode = Op.getOperand(5);
26693       unsigned Opc = IntrData->Opc0;
26694       if (HasRounding) {
26695         SDValue Sae = Op.getOperand(6);
26696         if (isRoundModeSAE(Sae))
26697           Opc = IntrWithRoundingModeOpcode;
26698         else if (!isRoundModeCurDirection(Sae))
26699           return SDValue();
26700       }
26701       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
26702                                               Src2, RoundingMode),
26703                                   Mask, passThru, Subtarget, DAG);
26704     }
26705     case INTR_TYPE_SCALAR_MASK_RND: {
26706       SDValue Src1 = Op.getOperand(1);
26707       SDValue Src2 = Op.getOperand(2);
26708       SDValue passThru = Op.getOperand(3);
26709       SDValue Mask = Op.getOperand(4);
26710       SDValue Rnd = Op.getOperand(5);
26711 
26712       SDValue NewOp;
26713       unsigned RC = 0;
26714       if (isRoundModeCurDirection(Rnd))
26715         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
26716       else if (isRoundModeSAEToX(Rnd, RC))
26717         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
26718                             DAG.getTargetConstant(RC, dl, MVT::i32));
26719       else
26720         return SDValue();
26721 
26722       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
26723     }
26724     case INTR_TYPE_SCALAR_MASK_SAE: {
26725       SDValue Src1 = Op.getOperand(1);
26726       SDValue Src2 = Op.getOperand(2);
26727       SDValue passThru = Op.getOperand(3);
26728       SDValue Mask = Op.getOperand(4);
26729       SDValue Sae = Op.getOperand(5);
26730       unsigned Opc;
26731       if (isRoundModeCurDirection(Sae))
26732         Opc = IntrData->Opc0;
26733       else if (isRoundModeSAE(Sae))
26734         Opc = IntrData->Opc1;
26735       else
26736         return SDValue();
26737 
26738       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
26739                                   Mask, passThru, Subtarget, DAG);
26740     }
26741     case INTR_TYPE_2OP_MASK: {
26742       SDValue Src1 = Op.getOperand(1);
26743       SDValue Src2 = Op.getOperand(2);
26744       SDValue PassThru = Op.getOperand(3);
26745       SDValue Mask = Op.getOperand(4);
26746       SDValue NewOp;
26747       if (IntrData->Opc1 != 0) {
26748         SDValue Rnd = Op.getOperand(5);
26749         unsigned RC = 0;
26750         if (isRoundModeSAEToX(Rnd, RC))
26751           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
26752                               DAG.getTargetConstant(RC, dl, MVT::i32));
26753         else if (!isRoundModeCurDirection(Rnd))
26754           return SDValue();
26755       }
26756       if (!NewOp)
26757         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
26758       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
26759     }
26760     case INTR_TYPE_2OP_MASK_SAE: {
26761       SDValue Src1 = Op.getOperand(1);
26762       SDValue Src2 = Op.getOperand(2);
26763       SDValue PassThru = Op.getOperand(3);
26764       SDValue Mask = Op.getOperand(4);
26765 
26766       unsigned Opc = IntrData->Opc0;
26767       if (IntrData->Opc1 != 0) {
26768         SDValue Sae = Op.getOperand(5);
26769         if (isRoundModeSAE(Sae))
26770           Opc = IntrData->Opc1;
26771         else if (!isRoundModeCurDirection(Sae))
26772           return SDValue();
26773       }
26774 
26775       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
26776                                   Mask, PassThru, Subtarget, DAG);
26777     }
26778     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
26779       SDValue Src1 = Op.getOperand(1);
26780       SDValue Src2 = Op.getOperand(2);
26781       SDValue Src3 = Op.getOperand(3);
26782       SDValue PassThru = Op.getOperand(4);
26783       SDValue Mask = Op.getOperand(5);
26784       SDValue Sae = Op.getOperand(6);
26785       unsigned Opc;
26786       if (isRoundModeCurDirection(Sae))
26787         Opc = IntrData->Opc0;
26788       else if (isRoundModeSAE(Sae))
26789         Opc = IntrData->Opc1;
26790       else
26791         return SDValue();
26792 
26793       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
26794                                   Mask, PassThru, Subtarget, DAG);
26795     }
26796     case INTR_TYPE_3OP_MASK_SAE: {
26797       SDValue Src1 = Op.getOperand(1);
26798       SDValue Src2 = Op.getOperand(2);
26799       SDValue Src3 = Op.getOperand(3);
26800       SDValue PassThru = Op.getOperand(4);
26801       SDValue Mask = Op.getOperand(5);
26802 
26803       unsigned Opc = IntrData->Opc0;
26804       if (IntrData->Opc1 != 0) {
26805         SDValue Sae = Op.getOperand(6);
26806         if (isRoundModeSAE(Sae))
26807           Opc = IntrData->Opc1;
26808         else if (!isRoundModeCurDirection(Sae))
26809           return SDValue();
26810       }
26811       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
26812                                   Mask, PassThru, Subtarget, DAG);
26813     }
26814     case BLENDV: {
26815       SDValue Src1 = Op.getOperand(1);
26816       SDValue Src2 = Op.getOperand(2);
26817       SDValue Src3 = Op.getOperand(3);
26818 
26819       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
26820       Src3 = DAG.getBitcast(MaskVT, Src3);
26821 
26822       // Reverse the operands to match VSELECT order.
26823       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
26824     }
26825     case VPERM_2OP : {
26826       SDValue Src1 = Op.getOperand(1);
26827       SDValue Src2 = Op.getOperand(2);
26828 
26829       // Swap Src1 and Src2 in the node creation
26830       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
26831     }
26832     case CFMA_OP_MASKZ:
26833     case CFMA_OP_MASK: {
26834       SDValue Src1 = Op.getOperand(1);
26835       SDValue Src2 = Op.getOperand(2);
26836       SDValue Src3 = Op.getOperand(3);
26837       SDValue Mask = Op.getOperand(4);
26838       MVT VT = Op.getSimpleValueType();
26839 
26840       SDValue PassThru = Src3;
26841       if (IntrData->Type == CFMA_OP_MASKZ)
26842         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
26843 
26844       // We add rounding mode to the Node when
26845       //   - RC Opcode is specified and
26846       //   - RC is not "current direction".
26847       SDValue NewOp;
26848       if (IntrData->Opc1 != 0) {
26849         SDValue Rnd = Op.getOperand(5);
26850         unsigned RC = 0;
26851         if (isRoundModeSAEToX(Rnd, RC))
26852           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2, Src3,
26853                               DAG.getTargetConstant(RC, dl, MVT::i32));
26854         else if (!isRoundModeCurDirection(Rnd))
26855           return SDValue();
26856       }
26857       if (!NewOp)
26858         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2, Src3);
26859       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
26860     }
26861     case IFMA_OP:
26862       // NOTE: We need to swizzle the operands to pass the multiply operands
26863       // first.
26864       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26865                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
26866     case FPCLASSS: {
26867       SDValue Src1 = Op.getOperand(1);
26868       SDValue Imm = Op.getOperand(2);
26869       SDValue Mask = Op.getOperand(3);
26870       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
26871       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
26872                                                  Subtarget, DAG);
26873       // Need to fill with zeros to ensure the bitcast will produce zeroes
26874       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26875       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
26876                                 DAG.getConstant(0, dl, MVT::v8i1),
26877                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
26878       return DAG.getBitcast(MVT::i8, Ins);
26879     }
26880 
26881     case CMP_MASK_CC: {
26882       MVT MaskVT = Op.getSimpleValueType();
26883       SDValue CC = Op.getOperand(3);
26884       SDValue Mask = Op.getOperand(4);
26885       // We specify 2 possible opcodes for intrinsics with rounding modes.
26886       // First, we check if the intrinsic may have non-default rounding mode,
26887       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
26888       if (IntrData->Opc1 != 0) {
26889         SDValue Sae = Op.getOperand(5);
26890         if (isRoundModeSAE(Sae))
26891           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
26892                              Op.getOperand(2), CC, Mask, Sae);
26893         if (!isRoundModeCurDirection(Sae))
26894           return SDValue();
26895       }
26896       //default rounding mode
26897       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
26898                          {Op.getOperand(1), Op.getOperand(2), CC, Mask});
26899     }
26900     case CMP_MASK_SCALAR_CC: {
26901       SDValue Src1 = Op.getOperand(1);
26902       SDValue Src2 = Op.getOperand(2);
26903       SDValue CC = Op.getOperand(3);
26904       SDValue Mask = Op.getOperand(4);
26905 
26906       SDValue Cmp;
26907       if (IntrData->Opc1 != 0) {
26908         SDValue Sae = Op.getOperand(5);
26909         if (isRoundModeSAE(Sae))
26910           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
26911         else if (!isRoundModeCurDirection(Sae))
26912           return SDValue();
26913       }
26914       //default rounding mode
26915       if (!Cmp.getNode())
26916         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
26917 
26918       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
26919                                              Subtarget, DAG);
26920       // Need to fill with zeros to ensure the bitcast will produce zeroes
26921       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26922       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
26923                                 DAG.getConstant(0, dl, MVT::v8i1),
26924                                 CmpMask, DAG.getIntPtrConstant(0, dl));
26925       return DAG.getBitcast(MVT::i8, Ins);
26926     }
26927     case COMI: { // Comparison intrinsics
26928       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
26929       SDValue LHS = Op.getOperand(1);
26930       SDValue RHS = Op.getOperand(2);
26931       // Some conditions require the operands to be swapped.
26932       if (CC == ISD::SETLT || CC == ISD::SETLE)
26933         std::swap(LHS, RHS);
26934 
26935       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
26936       SDValue SetCC;
26937       switch (CC) {
26938       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
26939         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
26940         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
26941         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
26942         break;
26943       }
26944       case ISD::SETNE: { // (ZF = 1 or PF = 1)
26945         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
26946         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
26947         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
26948         break;
26949       }
26950       case ISD::SETGT: // (CF = 0 and ZF = 0)
26951       case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
26952         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
26953         break;
26954       }
26955       case ISD::SETGE: // CF = 0
26956       case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
26957         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
26958         break;
26959       default:
26960         llvm_unreachable("Unexpected illegal condition!");
26961       }
26962       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26963     }
26964     case COMI_RM: { // Comparison intrinsics with Sae
26965       SDValue LHS = Op.getOperand(1);
26966       SDValue RHS = Op.getOperand(2);
26967       unsigned CondVal = Op.getConstantOperandVal(3);
26968       SDValue Sae = Op.getOperand(4);
26969 
26970       SDValue FCmp;
26971       if (isRoundModeCurDirection(Sae))
26972         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
26973                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
26974       else if (isRoundModeSAE(Sae))
26975         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
26976                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
26977       else
26978         return SDValue();
26979       // Need to fill with zeros to ensure the bitcast will produce zeroes
26980       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26981       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
26982                                 DAG.getConstant(0, dl, MVT::v16i1),
26983                                 FCmp, DAG.getIntPtrConstant(0, dl));
26984       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
26985                          DAG.getBitcast(MVT::i16, Ins));
26986     }
26987     case VSHIFT: {
26988       SDValue SrcOp = Op.getOperand(1);
26989       SDValue ShAmt = Op.getOperand(2);
26990       assert(ShAmt.getValueType() == MVT::i32 &&
26991              "Unexpected VSHIFT amount type");
26992 
26993       // Catch shift-by-constant.
26994       if (auto *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
26995         return getTargetVShiftByConstNode(IntrData->Opc0, dl,
26996                                           Op.getSimpleValueType(), SrcOp,
26997                                           CShAmt->getZExtValue(), DAG);
26998 
26999       ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
27000       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
27001                                  SrcOp, ShAmt, 0, Subtarget, DAG);
27002     }
27003     case COMPRESS_EXPAND_IN_REG: {
27004       SDValue Mask = Op.getOperand(3);
27005       SDValue DataToCompress = Op.getOperand(1);
27006       SDValue PassThru = Op.getOperand(2);
27007       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
27008         return Op.getOperand(1);
27009 
27010       // Avoid false dependency.
27011       if (PassThru.isUndef())
27012         PassThru = DAG.getConstant(0, dl, VT);
27013 
27014       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
27015                          Mask);
27016     }
27017     case FIXUPIMM:
27018     case FIXUPIMM_MASKZ: {
27019       SDValue Src1 = Op.getOperand(1);
27020       SDValue Src2 = Op.getOperand(2);
27021       SDValue Src3 = Op.getOperand(3);
27022       SDValue Imm = Op.getOperand(4);
27023       SDValue Mask = Op.getOperand(5);
27024       SDValue Passthru = (IntrData->Type == FIXUPIMM)
27025                              ? Src1
27026                              : getZeroVector(VT, Subtarget, DAG, dl);
27027 
27028       unsigned Opc = IntrData->Opc0;
27029       if (IntrData->Opc1 != 0) {
27030         SDValue Sae = Op.getOperand(6);
27031         if (isRoundModeSAE(Sae))
27032           Opc = IntrData->Opc1;
27033         else if (!isRoundModeCurDirection(Sae))
27034           return SDValue();
27035       }
27036 
27037       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
27038 
27039       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
27040         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
27041 
27042       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
27043     }
27044     case ROUNDP: {
27045       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
27046       // Clear the upper bits of the rounding immediate so that the legacy
27047       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
27048       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
27049       SDValue RoundingMode =
27050           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
27051       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
27052                          Op.getOperand(1), RoundingMode);
27053     }
27054     case ROUNDS: {
27055       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
27056       // Clear the upper bits of the rounding immediate so that the legacy
27057       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
27058       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
27059       SDValue RoundingMode =
27060           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
27061       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
27062                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
27063     }
27064     case BEXTRI: {
27065       assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode");
27066 
27067       uint64_t Imm = Op.getConstantOperandVal(2);
27068       SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
27069                                               Op.getValueType());
27070       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
27071                          Op.getOperand(1), Control);
27072     }
27073     // ADC/ADCX/SBB
27074     case ADX: {
27075       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
27076       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
27077 
27078       SDValue Res;
27079       // If the carry in is zero, then we should just use ADD/SUB instead of
27080       // ADC/SBB.
27081       if (isNullConstant(Op.getOperand(1))) {
27082         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
27083                           Op.getOperand(3));
27084       } else {
27085         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
27086                                     DAG.getConstant(-1, dl, MVT::i8));
27087         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
27088                           Op.getOperand(3), GenCF.getValue(1));
27089       }
27090       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
27091       SDValue Results[] = { SetCC, Res };
27092       return DAG.getMergeValues(Results, dl);
27093     }
27094     case CVTPD2PS_MASK:
27095     case CVTPD2DQ_MASK:
27096     case CVTQQ2PS_MASK:
27097     case TRUNCATE_TO_REG: {
27098       SDValue Src = Op.getOperand(1);
27099       SDValue PassThru = Op.getOperand(2);
27100       SDValue Mask = Op.getOperand(3);
27101 
27102       if (isAllOnesConstant(Mask))
27103         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
27104 
27105       MVT SrcVT = Src.getSimpleValueType();
27106       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
27107       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27108       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
27109                          {Src, PassThru, Mask});
27110     }
27111     case CVTPS2PH_MASK: {
27112       SDValue Src = Op.getOperand(1);
27113       SDValue Rnd = Op.getOperand(2);
27114       SDValue PassThru = Op.getOperand(3);
27115       SDValue Mask = Op.getOperand(4);
27116 
27117       if (isAllOnesConstant(Mask))
27118         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
27119 
27120       MVT SrcVT = Src.getSimpleValueType();
27121       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
27122       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27123       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
27124                          PassThru, Mask);
27125 
27126     }
27127     case CVTNEPS2BF16_MASK: {
27128       SDValue Src = Op.getOperand(1);
27129       SDValue PassThru = Op.getOperand(2);
27130       SDValue Mask = Op.getOperand(3);
27131 
27132       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
27133         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
27134 
27135       // Break false dependency.
27136       if (PassThru.isUndef())
27137         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
27138 
27139       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
27140                          Mask);
27141     }
27142     default:
27143       break;
27144     }
27145   }
27146 
27147   switch (IntNo) {
27148   default: return SDValue();    // Don't custom lower most intrinsics.
27149 
27150   // ptest and testp intrinsics. The intrinsic these come from are designed to
27151   // return an integer value, not just an instruction so lower it to the ptest
27152   // or testp pattern and a setcc for the result.
27153   case Intrinsic::x86_avx512_ktestc_b:
27154   case Intrinsic::x86_avx512_ktestc_w:
27155   case Intrinsic::x86_avx512_ktestc_d:
27156   case Intrinsic::x86_avx512_ktestc_q:
27157   case Intrinsic::x86_avx512_ktestz_b:
27158   case Intrinsic::x86_avx512_ktestz_w:
27159   case Intrinsic::x86_avx512_ktestz_d:
27160   case Intrinsic::x86_avx512_ktestz_q:
27161   case Intrinsic::x86_sse41_ptestz:
27162   case Intrinsic::x86_sse41_ptestc:
27163   case Intrinsic::x86_sse41_ptestnzc:
27164   case Intrinsic::x86_avx_ptestz_256:
27165   case Intrinsic::x86_avx_ptestc_256:
27166   case Intrinsic::x86_avx_ptestnzc_256:
27167   case Intrinsic::x86_avx_vtestz_ps:
27168   case Intrinsic::x86_avx_vtestc_ps:
27169   case Intrinsic::x86_avx_vtestnzc_ps:
27170   case Intrinsic::x86_avx_vtestz_pd:
27171   case Intrinsic::x86_avx_vtestc_pd:
27172   case Intrinsic::x86_avx_vtestnzc_pd:
27173   case Intrinsic::x86_avx_vtestz_ps_256:
27174   case Intrinsic::x86_avx_vtestc_ps_256:
27175   case Intrinsic::x86_avx_vtestnzc_ps_256:
27176   case Intrinsic::x86_avx_vtestz_pd_256:
27177   case Intrinsic::x86_avx_vtestc_pd_256:
27178   case Intrinsic::x86_avx_vtestnzc_pd_256: {
27179     unsigned TestOpc = X86ISD::PTEST;
27180     X86::CondCode X86CC;
27181     switch (IntNo) {
27182     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
27183     case Intrinsic::x86_avx512_ktestc_b:
27184     case Intrinsic::x86_avx512_ktestc_w:
27185     case Intrinsic::x86_avx512_ktestc_d:
27186     case Intrinsic::x86_avx512_ktestc_q:
27187       // CF = 1
27188       TestOpc = X86ISD::KTEST;
27189       X86CC = X86::COND_B;
27190       break;
27191     case Intrinsic::x86_avx512_ktestz_b:
27192     case Intrinsic::x86_avx512_ktestz_w:
27193     case Intrinsic::x86_avx512_ktestz_d:
27194     case Intrinsic::x86_avx512_ktestz_q:
27195       TestOpc = X86ISD::KTEST;
27196       X86CC = X86::COND_E;
27197       break;
27198     case Intrinsic::x86_avx_vtestz_ps:
27199     case Intrinsic::x86_avx_vtestz_pd:
27200     case Intrinsic::x86_avx_vtestz_ps_256:
27201     case Intrinsic::x86_avx_vtestz_pd_256:
27202       TestOpc = X86ISD::TESTP;
27203       LLVM_FALLTHROUGH;
27204     case Intrinsic::x86_sse41_ptestz:
27205     case Intrinsic::x86_avx_ptestz_256:
27206       // ZF = 1
27207       X86CC = X86::COND_E;
27208       break;
27209     case Intrinsic::x86_avx_vtestc_ps:
27210     case Intrinsic::x86_avx_vtestc_pd:
27211     case Intrinsic::x86_avx_vtestc_ps_256:
27212     case Intrinsic::x86_avx_vtestc_pd_256:
27213       TestOpc = X86ISD::TESTP;
27214       LLVM_FALLTHROUGH;
27215     case Intrinsic::x86_sse41_ptestc:
27216     case Intrinsic::x86_avx_ptestc_256:
27217       // CF = 1
27218       X86CC = X86::COND_B;
27219       break;
27220     case Intrinsic::x86_avx_vtestnzc_ps:
27221     case Intrinsic::x86_avx_vtestnzc_pd:
27222     case Intrinsic::x86_avx_vtestnzc_ps_256:
27223     case Intrinsic::x86_avx_vtestnzc_pd_256:
27224       TestOpc = X86ISD::TESTP;
27225       LLVM_FALLTHROUGH;
27226     case Intrinsic::x86_sse41_ptestnzc:
27227     case Intrinsic::x86_avx_ptestnzc_256:
27228       // ZF and CF = 0
27229       X86CC = X86::COND_A;
27230       break;
27231     }
27232 
27233     SDValue LHS = Op.getOperand(1);
27234     SDValue RHS = Op.getOperand(2);
27235     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
27236     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
27237     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
27238   }
27239 
27240   case Intrinsic::x86_sse42_pcmpistria128:
27241   case Intrinsic::x86_sse42_pcmpestria128:
27242   case Intrinsic::x86_sse42_pcmpistric128:
27243   case Intrinsic::x86_sse42_pcmpestric128:
27244   case Intrinsic::x86_sse42_pcmpistrio128:
27245   case Intrinsic::x86_sse42_pcmpestrio128:
27246   case Intrinsic::x86_sse42_pcmpistris128:
27247   case Intrinsic::x86_sse42_pcmpestris128:
27248   case Intrinsic::x86_sse42_pcmpistriz128:
27249   case Intrinsic::x86_sse42_pcmpestriz128: {
27250     unsigned Opcode;
27251     X86::CondCode X86CC;
27252     switch (IntNo) {
27253     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
27254     case Intrinsic::x86_sse42_pcmpistria128:
27255       Opcode = X86ISD::PCMPISTR;
27256       X86CC = X86::COND_A;
27257       break;
27258     case Intrinsic::x86_sse42_pcmpestria128:
27259       Opcode = X86ISD::PCMPESTR;
27260       X86CC = X86::COND_A;
27261       break;
27262     case Intrinsic::x86_sse42_pcmpistric128:
27263       Opcode = X86ISD::PCMPISTR;
27264       X86CC = X86::COND_B;
27265       break;
27266     case Intrinsic::x86_sse42_pcmpestric128:
27267       Opcode = X86ISD::PCMPESTR;
27268       X86CC = X86::COND_B;
27269       break;
27270     case Intrinsic::x86_sse42_pcmpistrio128:
27271       Opcode = X86ISD::PCMPISTR;
27272       X86CC = X86::COND_O;
27273       break;
27274     case Intrinsic::x86_sse42_pcmpestrio128:
27275       Opcode = X86ISD::PCMPESTR;
27276       X86CC = X86::COND_O;
27277       break;
27278     case Intrinsic::x86_sse42_pcmpistris128:
27279       Opcode = X86ISD::PCMPISTR;
27280       X86CC = X86::COND_S;
27281       break;
27282     case Intrinsic::x86_sse42_pcmpestris128:
27283       Opcode = X86ISD::PCMPESTR;
27284       X86CC = X86::COND_S;
27285       break;
27286     case Intrinsic::x86_sse42_pcmpistriz128:
27287       Opcode = X86ISD::PCMPISTR;
27288       X86CC = X86::COND_E;
27289       break;
27290     case Intrinsic::x86_sse42_pcmpestriz128:
27291       Opcode = X86ISD::PCMPESTR;
27292       X86CC = X86::COND_E;
27293       break;
27294     }
27295     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
27296     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
27297     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
27298     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
27299     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
27300   }
27301 
27302   case Intrinsic::x86_sse42_pcmpistri128:
27303   case Intrinsic::x86_sse42_pcmpestri128: {
27304     unsigned Opcode;
27305     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
27306       Opcode = X86ISD::PCMPISTR;
27307     else
27308       Opcode = X86ISD::PCMPESTR;
27309 
27310     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
27311     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
27312     return DAG.getNode(Opcode, dl, VTs, NewOps);
27313   }
27314 
27315   case Intrinsic::x86_sse42_pcmpistrm128:
27316   case Intrinsic::x86_sse42_pcmpestrm128: {
27317     unsigned Opcode;
27318     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
27319       Opcode = X86ISD::PCMPISTR;
27320     else
27321       Opcode = X86ISD::PCMPESTR;
27322 
27323     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
27324     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
27325     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
27326   }
27327 
27328   case Intrinsic::eh_sjlj_lsda: {
27329     MachineFunction &MF = DAG.getMachineFunction();
27330     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27331     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
27332     auto &Context = MF.getMMI().getContext();
27333     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
27334                                             Twine(MF.getFunctionNumber()));
27335     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
27336                        DAG.getMCSymbol(S, PtrVT));
27337   }
27338 
27339   case Intrinsic::x86_seh_lsda: {
27340     // Compute the symbol for the LSDA. We know it'll get emitted later.
27341     MachineFunction &MF = DAG.getMachineFunction();
27342     SDValue Op1 = Op.getOperand(1);
27343     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
27344     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
27345         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
27346 
27347     // Generate a simple absolute symbol reference. This intrinsic is only
27348     // supported on 32-bit Windows, which isn't PIC.
27349     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
27350     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
27351   }
27352 
27353   case Intrinsic::eh_recoverfp: {
27354     SDValue FnOp = Op.getOperand(1);
27355     SDValue IncomingFPOp = Op.getOperand(2);
27356     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
27357     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
27358     if (!Fn)
27359       report_fatal_error(
27360           "llvm.eh.recoverfp must take a function as the first argument");
27361     return recoverFramePointer(DAG, Fn, IncomingFPOp);
27362   }
27363 
27364   case Intrinsic::localaddress: {
27365     // Returns one of the stack, base, or frame pointer registers, depending on
27366     // which is used to reference local variables.
27367     MachineFunction &MF = DAG.getMachineFunction();
27368     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27369     unsigned Reg;
27370     if (RegInfo->hasBasePointer(MF))
27371       Reg = RegInfo->getBaseRegister();
27372     else { // Handles the SP or FP case.
27373       bool CantUseFP = RegInfo->hasStackRealignment(MF);
27374       if (CantUseFP)
27375         Reg = RegInfo->getPtrSizedStackRegister(MF);
27376       else
27377         Reg = RegInfo->getPtrSizedFrameRegister(MF);
27378     }
27379     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
27380   }
27381   case Intrinsic::x86_avx512_vp2intersect_q_512:
27382   case Intrinsic::x86_avx512_vp2intersect_q_256:
27383   case Intrinsic::x86_avx512_vp2intersect_q_128:
27384   case Intrinsic::x86_avx512_vp2intersect_d_512:
27385   case Intrinsic::x86_avx512_vp2intersect_d_256:
27386   case Intrinsic::x86_avx512_vp2intersect_d_128: {
27387     MVT MaskVT = Op.getSimpleValueType();
27388 
27389     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
27390     SDLoc DL(Op);
27391 
27392     SDValue Operation =
27393         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
27394                     Op->getOperand(1), Op->getOperand(2));
27395 
27396     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
27397                                                  MaskVT, Operation);
27398     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
27399                                                  MaskVT, Operation);
27400     return DAG.getMergeValues({Result0, Result1}, DL);
27401   }
27402   case Intrinsic::x86_mmx_pslli_w:
27403   case Intrinsic::x86_mmx_pslli_d:
27404   case Intrinsic::x86_mmx_pslli_q:
27405   case Intrinsic::x86_mmx_psrli_w:
27406   case Intrinsic::x86_mmx_psrli_d:
27407   case Intrinsic::x86_mmx_psrli_q:
27408   case Intrinsic::x86_mmx_psrai_w:
27409   case Intrinsic::x86_mmx_psrai_d: {
27410     SDLoc DL(Op);
27411     SDValue ShAmt = Op.getOperand(2);
27412     // If the argument is a constant, convert it to a target constant.
27413     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
27414       // Clamp out of bounds shift amounts since they will otherwise be masked
27415       // to 8-bits which may make it no longer out of bounds.
27416       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
27417       if (ShiftAmount == 0)
27418         return Op.getOperand(1);
27419 
27420       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
27421                          Op.getOperand(0), Op.getOperand(1),
27422                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
27423     }
27424 
27425     unsigned NewIntrinsic;
27426     switch (IntNo) {
27427     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
27428     case Intrinsic::x86_mmx_pslli_w:
27429       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
27430       break;
27431     case Intrinsic::x86_mmx_pslli_d:
27432       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
27433       break;
27434     case Intrinsic::x86_mmx_pslli_q:
27435       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
27436       break;
27437     case Intrinsic::x86_mmx_psrli_w:
27438       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
27439       break;
27440     case Intrinsic::x86_mmx_psrli_d:
27441       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
27442       break;
27443     case Intrinsic::x86_mmx_psrli_q:
27444       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
27445       break;
27446     case Intrinsic::x86_mmx_psrai_w:
27447       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
27448       break;
27449     case Intrinsic::x86_mmx_psrai_d:
27450       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
27451       break;
27452     }
27453 
27454     // The vector shift intrinsics with scalars uses 32b shift amounts but
27455     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
27456     // MMX register.
27457     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
27458     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
27459                        DAG.getTargetConstant(NewIntrinsic, DL,
27460                                              getPointerTy(DAG.getDataLayout())),
27461                        Op.getOperand(1), ShAmt);
27462   }
27463   case Intrinsic::thread_pointer: {
27464     if (Subtarget.isTargetELF()) {
27465       SDLoc dl(Op);
27466       EVT PtrVT = getPointerTy(DAG.getDataLayout());
27467       // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
27468       Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(
27469           *DAG.getContext(), Subtarget.is64Bit() ? X86AS::FS : X86AS::GS));
27470       return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
27471                          DAG.getIntPtrConstant(0, dl), MachinePointerInfo(Ptr));
27472     }
27473     report_fatal_error(
27474         "Target OS doesn't support __builtin_thread_pointer() yet.");
27475   }
27476   }
27477 }
27478 
27479 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
27480                                  SDValue Src, SDValue Mask, SDValue Base,
27481                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
27482                                  const X86Subtarget &Subtarget) {
27483   SDLoc dl(Op);
27484   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
27485   // Scale must be constant.
27486   if (!C)
27487     return SDValue();
27488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27489   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
27490                                         TLI.getPointerTy(DAG.getDataLayout()));
27491   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
27492   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
27493   // If source is undef or we know it won't be used, use a zero vector
27494   // to break register dependency.
27495   // TODO: use undef instead and let BreakFalseDeps deal with it?
27496   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
27497     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
27498 
27499   // Cast mask to an integer type.
27500   Mask = DAG.getBitcast(MaskVT, Mask);
27501 
27502   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27503 
27504   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
27505   SDValue Res =
27506       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
27507                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
27508   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
27509 }
27510 
27511 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
27512                              SDValue Src, SDValue Mask, SDValue Base,
27513                              SDValue Index, SDValue ScaleOp, SDValue Chain,
27514                              const X86Subtarget &Subtarget) {
27515   MVT VT = Op.getSimpleValueType();
27516   SDLoc dl(Op);
27517   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
27518   // Scale must be constant.
27519   if (!C)
27520     return SDValue();
27521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27522   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
27523                                         TLI.getPointerTy(DAG.getDataLayout()));
27524   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
27525                               VT.getVectorNumElements());
27526   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
27527 
27528   // We support two versions of the gather intrinsics. One with scalar mask and
27529   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
27530   if (Mask.getValueType() != MaskVT)
27531     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27532 
27533   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
27534   // If source is undef or we know it won't be used, use a zero vector
27535   // to break register dependency.
27536   // TODO: use undef instead and let BreakFalseDeps deal with it?
27537   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
27538     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
27539 
27540   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27541 
27542   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
27543   SDValue Res =
27544       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
27545                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
27546   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
27547 }
27548 
27549 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
27550                                SDValue Src, SDValue Mask, SDValue Base,
27551                                SDValue Index, SDValue ScaleOp, SDValue Chain,
27552                                const X86Subtarget &Subtarget) {
27553   SDLoc dl(Op);
27554   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
27555   // Scale must be constant.
27556   if (!C)
27557     return SDValue();
27558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27559   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
27560                                         TLI.getPointerTy(DAG.getDataLayout()));
27561   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
27562                               Src.getSimpleValueType().getVectorNumElements());
27563   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
27564 
27565   // We support two versions of the scatter intrinsics. One with scalar mask and
27566   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
27567   if (Mask.getValueType() != MaskVT)
27568     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27569 
27570   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27571 
27572   SDVTList VTs = DAG.getVTList(MVT::Other);
27573   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
27574   SDValue Res =
27575       DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
27576                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
27577   return Res;
27578 }
27579 
27580 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
27581                                SDValue Mask, SDValue Base, SDValue Index,
27582                                SDValue ScaleOp, SDValue Chain,
27583                                const X86Subtarget &Subtarget) {
27584   SDLoc dl(Op);
27585   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
27586   // Scale must be constant.
27587   if (!C)
27588     return SDValue();
27589   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27590   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
27591                                         TLI.getPointerTy(DAG.getDataLayout()));
27592   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
27593   SDValue Segment = DAG.getRegister(0, MVT::i32);
27594   MVT MaskVT =
27595     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
27596   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27597   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
27598   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
27599   return SDValue(Res, 0);
27600 }
27601 
27602 /// Handles the lowering of builtin intrinsics with chain that return their
27603 /// value into registers EDX:EAX.
27604 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
27605 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
27606 /// TargetOpcode.
27607 /// Returns a Glue value which can be used to add extra copy-from-reg if the
27608 /// expanded intrinsics implicitly defines extra registers (i.e. not just
27609 /// EDX:EAX).
27610 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
27611                                         SelectionDAG &DAG,
27612                                         unsigned TargetOpcode,
27613                                         unsigned SrcReg,
27614                                         const X86Subtarget &Subtarget,
27615                                         SmallVectorImpl<SDValue> &Results) {
27616   SDValue Chain = N->getOperand(0);
27617   SDValue Glue;
27618 
27619   if (SrcReg) {
27620     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
27621     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
27622     Glue = Chain.getValue(1);
27623   }
27624 
27625   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
27626   SDValue N1Ops[] = {Chain, Glue};
27627   SDNode *N1 = DAG.getMachineNode(
27628       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
27629   Chain = SDValue(N1, 0);
27630 
27631   // Reads the content of XCR and returns it in registers EDX:EAX.
27632   SDValue LO, HI;
27633   if (Subtarget.is64Bit()) {
27634     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
27635     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
27636                             LO.getValue(2));
27637   } else {
27638     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
27639     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
27640                             LO.getValue(2));
27641   }
27642   Chain = HI.getValue(1);
27643   Glue = HI.getValue(2);
27644 
27645   if (Subtarget.is64Bit()) {
27646     // Merge the two 32-bit values into a 64-bit one.
27647     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
27648                               DAG.getConstant(32, DL, MVT::i8));
27649     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
27650     Results.push_back(Chain);
27651     return Glue;
27652   }
27653 
27654   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
27655   SDValue Ops[] = { LO, HI };
27656   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
27657   Results.push_back(Pair);
27658   Results.push_back(Chain);
27659   return Glue;
27660 }
27661 
27662 /// Handles the lowering of builtin intrinsics that read the time stamp counter
27663 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
27664 /// READCYCLECOUNTER nodes.
27665 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
27666                                     SelectionDAG &DAG,
27667                                     const X86Subtarget &Subtarget,
27668                                     SmallVectorImpl<SDValue> &Results) {
27669   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
27670   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
27671   // and the EAX register is loaded with the low-order 32 bits.
27672   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
27673                                              /* NoRegister */0, Subtarget,
27674                                              Results);
27675   if (Opcode != X86::RDTSCP)
27676     return;
27677 
27678   SDValue Chain = Results[1];
27679   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
27680   // the ECX register. Add 'ecx' explicitly to the chain.
27681   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
27682   Results[1] = ecx;
27683   Results.push_back(ecx.getValue(1));
27684 }
27685 
27686 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
27687                                      SelectionDAG &DAG) {
27688   SmallVector<SDValue, 3> Results;
27689   SDLoc DL(Op);
27690   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
27691                           Results);
27692   return DAG.getMergeValues(Results, DL);
27693 }
27694 
27695 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
27696   MachineFunction &MF = DAG.getMachineFunction();
27697   SDValue Chain = Op.getOperand(0);
27698   SDValue RegNode = Op.getOperand(2);
27699   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
27700   if (!EHInfo)
27701     report_fatal_error("EH registrations only live in functions using WinEH");
27702 
27703   // Cast the operand to an alloca, and remember the frame index.
27704   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
27705   if (!FINode)
27706     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
27707   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
27708 
27709   // Return the chain operand without making any DAG nodes.
27710   return Chain;
27711 }
27712 
27713 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
27714   MachineFunction &MF = DAG.getMachineFunction();
27715   SDValue Chain = Op.getOperand(0);
27716   SDValue EHGuard = Op.getOperand(2);
27717   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
27718   if (!EHInfo)
27719     report_fatal_error("EHGuard only live in functions using WinEH");
27720 
27721   // Cast the operand to an alloca, and remember the frame index.
27722   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
27723   if (!FINode)
27724     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
27725   EHInfo->EHGuardFrameIndex = FINode->getIndex();
27726 
27727   // Return the chain operand without making any DAG nodes.
27728   return Chain;
27729 }
27730 
27731 /// Emit Truncating Store with signed or unsigned saturation.
27732 static SDValue
27733 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
27734                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
27735                 SelectionDAG &DAG) {
27736   SDVTList VTs = DAG.getVTList(MVT::Other);
27737   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
27738   SDValue Ops[] = { Chain, Val, Ptr, Undef };
27739   unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
27740   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
27741 }
27742 
27743 /// Emit Masked Truncating Store with signed or unsigned saturation.
27744 static SDValue
27745 EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
27746                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
27747                       MachineMemOperand *MMO, SelectionDAG &DAG) {
27748   SDVTList VTs = DAG.getVTList(MVT::Other);
27749   SDValue Ops[] = { Chain, Val, Ptr, Mask };
27750   unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
27751   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
27752 }
27753 
27754 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
27755                                       SelectionDAG &DAG) {
27756   unsigned IntNo = Op.getConstantOperandVal(1);
27757   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
27758   if (!IntrData) {
27759     switch (IntNo) {
27760 
27761     case Intrinsic::swift_async_context_addr: {
27762       SDLoc dl(Op);
27763       auto &MF = DAG.getMachineFunction();
27764       auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
27765       if (Subtarget.is64Bit()) {
27766         MF.getFrameInfo().setFrameAddressIsTaken(true);
27767         X86FI->setHasSwiftAsyncContext(true);
27768         SDValue Chain = Op->getOperand(0);
27769         SDValue CopyRBP = DAG.getCopyFromReg(Chain, dl, X86::RBP, MVT::i64);
27770         SDValue Result =
27771             SDValue(DAG.getMachineNode(X86::SUB64ri8, dl, MVT::i64, CopyRBP,
27772                                        DAG.getTargetConstant(8, dl, MVT::i32)),
27773                     0);
27774         // Return { result, chain }.
27775         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
27776                            CopyRBP.getValue(1));
27777       } else {
27778         // 32-bit so no special extended frame, create or reuse an existing
27779         // stack slot.
27780         if (!X86FI->getSwiftAsyncContextFrameIdx())
27781           X86FI->setSwiftAsyncContextFrameIdx(
27782               MF.getFrameInfo().CreateStackObject(4, Align(4), false));
27783         SDValue Result =
27784             DAG.getFrameIndex(*X86FI->getSwiftAsyncContextFrameIdx(), MVT::i32);
27785         // Return { result, chain }.
27786         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
27787                            Op->getOperand(0));
27788       }
27789     }
27790 
27791     case llvm::Intrinsic::x86_seh_ehregnode:
27792       return MarkEHRegistrationNode(Op, DAG);
27793     case llvm::Intrinsic::x86_seh_ehguard:
27794       return MarkEHGuard(Op, DAG);
27795     case llvm::Intrinsic::x86_rdpkru: {
27796       SDLoc dl(Op);
27797       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27798       // Create a RDPKRU node and pass 0 to the ECX parameter.
27799       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
27800                          DAG.getConstant(0, dl, MVT::i32));
27801     }
27802     case llvm::Intrinsic::x86_wrpkru: {
27803       SDLoc dl(Op);
27804       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
27805       // to the EDX and ECX parameters.
27806       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
27807                          Op.getOperand(0), Op.getOperand(2),
27808                          DAG.getConstant(0, dl, MVT::i32),
27809                          DAG.getConstant(0, dl, MVT::i32));
27810     }
27811     case llvm::Intrinsic::asan_check_memaccess: {
27812       // Mark this as adjustsStack because it will be lowered to a call.
27813       DAG.getMachineFunction().getFrameInfo().setAdjustsStack(true);
27814       // Don't do anything here, we will expand these intrinsics out later.
27815       return Op;
27816     }
27817     case llvm::Intrinsic::x86_flags_read_u32:
27818     case llvm::Intrinsic::x86_flags_read_u64:
27819     case llvm::Intrinsic::x86_flags_write_u32:
27820     case llvm::Intrinsic::x86_flags_write_u64: {
27821       // We need a frame pointer because this will get lowered to a PUSH/POP
27822       // sequence.
27823       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
27824       MFI.setHasCopyImplyingStackAdjustment(true);
27825       // Don't do anything here, we will expand these intrinsics out later
27826       // during FinalizeISel in EmitInstrWithCustomInserter.
27827       return Op;
27828     }
27829     case Intrinsic::x86_lwpins32:
27830     case Intrinsic::x86_lwpins64:
27831     case Intrinsic::x86_umwait:
27832     case Intrinsic::x86_tpause: {
27833       SDLoc dl(Op);
27834       SDValue Chain = Op->getOperand(0);
27835       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27836       unsigned Opcode;
27837 
27838       switch (IntNo) {
27839       default: llvm_unreachable("Impossible intrinsic");
27840       case Intrinsic::x86_umwait:
27841         Opcode = X86ISD::UMWAIT;
27842         break;
27843       case Intrinsic::x86_tpause:
27844         Opcode = X86ISD::TPAUSE;
27845         break;
27846       case Intrinsic::x86_lwpins32:
27847       case Intrinsic::x86_lwpins64:
27848         Opcode = X86ISD::LWPINS;
27849         break;
27850       }
27851 
27852       SDValue Operation =
27853           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
27854                       Op->getOperand(3), Op->getOperand(4));
27855       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
27856       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27857                          Operation.getValue(1));
27858     }
27859     case Intrinsic::x86_enqcmd:
27860     case Intrinsic::x86_enqcmds: {
27861       SDLoc dl(Op);
27862       SDValue Chain = Op.getOperand(0);
27863       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27864       unsigned Opcode;
27865       switch (IntNo) {
27866       default: llvm_unreachable("Impossible intrinsic!");
27867       case Intrinsic::x86_enqcmd:
27868         Opcode = X86ISD::ENQCMD;
27869         break;
27870       case Intrinsic::x86_enqcmds:
27871         Opcode = X86ISD::ENQCMDS;
27872         break;
27873       }
27874       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
27875                                       Op.getOperand(3));
27876       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
27877       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27878                          Operation.getValue(1));
27879     }
27880     case Intrinsic::x86_aesenc128kl:
27881     case Intrinsic::x86_aesdec128kl:
27882     case Intrinsic::x86_aesenc256kl:
27883     case Intrinsic::x86_aesdec256kl: {
27884       SDLoc DL(Op);
27885       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
27886       SDValue Chain = Op.getOperand(0);
27887       unsigned Opcode;
27888 
27889       switch (IntNo) {
27890       default: llvm_unreachable("Impossible intrinsic");
27891       case Intrinsic::x86_aesenc128kl:
27892         Opcode = X86ISD::AESENC128KL;
27893         break;
27894       case Intrinsic::x86_aesdec128kl:
27895         Opcode = X86ISD::AESDEC128KL;
27896         break;
27897       case Intrinsic::x86_aesenc256kl:
27898         Opcode = X86ISD::AESENC256KL;
27899         break;
27900       case Intrinsic::x86_aesdec256kl:
27901         Opcode = X86ISD::AESDEC256KL;
27902         break;
27903       }
27904 
27905       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27906       MachineMemOperand *MMO = MemIntr->getMemOperand();
27907       EVT MemVT = MemIntr->getMemoryVT();
27908       SDValue Operation = DAG.getMemIntrinsicNode(
27909           Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
27910           MMO);
27911       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
27912 
27913       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27914                          {ZF, Operation.getValue(0), Operation.getValue(2)});
27915     }
27916     case Intrinsic::x86_aesencwide128kl:
27917     case Intrinsic::x86_aesdecwide128kl:
27918     case Intrinsic::x86_aesencwide256kl:
27919     case Intrinsic::x86_aesdecwide256kl: {
27920       SDLoc DL(Op);
27921       SDVTList VTs = DAG.getVTList(
27922           {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
27923            MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
27924       SDValue Chain = Op.getOperand(0);
27925       unsigned Opcode;
27926 
27927       switch (IntNo) {
27928       default: llvm_unreachable("Impossible intrinsic");
27929       case Intrinsic::x86_aesencwide128kl:
27930         Opcode = X86ISD::AESENCWIDE128KL;
27931         break;
27932       case Intrinsic::x86_aesdecwide128kl:
27933         Opcode = X86ISD::AESDECWIDE128KL;
27934         break;
27935       case Intrinsic::x86_aesencwide256kl:
27936         Opcode = X86ISD::AESENCWIDE256KL;
27937         break;
27938       case Intrinsic::x86_aesdecwide256kl:
27939         Opcode = X86ISD::AESDECWIDE256KL;
27940         break;
27941       }
27942 
27943       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27944       MachineMemOperand *MMO = MemIntr->getMemOperand();
27945       EVT MemVT = MemIntr->getMemoryVT();
27946       SDValue Operation = DAG.getMemIntrinsicNode(
27947           Opcode, DL, VTs,
27948           {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
27949            Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
27950            Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
27951           MemVT, MMO);
27952       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
27953 
27954       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27955                          {ZF, Operation.getValue(1), Operation.getValue(2),
27956                           Operation.getValue(3), Operation.getValue(4),
27957                           Operation.getValue(5), Operation.getValue(6),
27958                           Operation.getValue(7), Operation.getValue(8),
27959                           Operation.getValue(9)});
27960     }
27961     case Intrinsic::x86_testui: {
27962       SDLoc dl(Op);
27963       SDValue Chain = Op.getOperand(0);
27964       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27965       SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
27966       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
27967       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27968                          Operation.getValue(1));
27969     }
27970     case Intrinsic::x86_atomic_bts:
27971     case Intrinsic::x86_atomic_btc:
27972     case Intrinsic::x86_atomic_btr: {
27973       SDLoc DL(Op);
27974       MVT VT = Op.getSimpleValueType();
27975       SDValue Chain = Op.getOperand(0);
27976       SDValue Op1 = Op.getOperand(2);
27977       SDValue Op2 = Op.getOperand(3);
27978       unsigned Opc = IntNo == Intrinsic::x86_atomic_bts   ? X86ISD::LBTS
27979                      : IntNo == Intrinsic::x86_atomic_btc ? X86ISD::LBTC
27980                                                           : X86ISD::LBTR;
27981       SDValue Size = DAG.getConstant(VT.getScalarSizeInBits(), DL, MVT::i32);
27982       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
27983       SDValue Res =
27984           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
27985                                   {Chain, Op1, Op2, Size}, VT, MMO);
27986       Chain = Res.getValue(1);
27987       Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
27988       unsigned Imm = cast<ConstantSDNode>(Op2)->getZExtValue();
27989       if (Imm)
27990         Res = DAG.getNode(ISD::SHL, DL, VT, Res,
27991                           DAG.getShiftAmountConstant(Imm, VT, DL));
27992       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
27993     }
27994     }
27995     return SDValue();
27996   }
27997 
27998   SDLoc dl(Op);
27999   switch(IntrData->Type) {
28000   default: llvm_unreachable("Unknown Intrinsic Type");
28001   case RDSEED:
28002   case RDRAND: {
28003     // Emit the node with the right value type.
28004     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
28005     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
28006 
28007     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
28008     // Otherwise return the value from Rand, which is always 0, casted to i32.
28009     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
28010                      DAG.getConstant(1, dl, Op->getValueType(1)),
28011                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
28012                      SDValue(Result.getNode(), 1)};
28013     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
28014 
28015     // Return { result, isValid, chain }.
28016     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
28017                        SDValue(Result.getNode(), 2));
28018   }
28019   case GATHER_AVX2: {
28020     SDValue Chain = Op.getOperand(0);
28021     SDValue Src   = Op.getOperand(2);
28022     SDValue Base  = Op.getOperand(3);
28023     SDValue Index = Op.getOperand(4);
28024     SDValue Mask  = Op.getOperand(5);
28025     SDValue Scale = Op.getOperand(6);
28026     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
28027                              Scale, Chain, Subtarget);
28028   }
28029   case GATHER: {
28030   //gather(v1, mask, index, base, scale);
28031     SDValue Chain = Op.getOperand(0);
28032     SDValue Src   = Op.getOperand(2);
28033     SDValue Base  = Op.getOperand(3);
28034     SDValue Index = Op.getOperand(4);
28035     SDValue Mask  = Op.getOperand(5);
28036     SDValue Scale = Op.getOperand(6);
28037     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
28038                          Chain, Subtarget);
28039   }
28040   case SCATTER: {
28041   //scatter(base, mask, index, v1, scale);
28042     SDValue Chain = Op.getOperand(0);
28043     SDValue Base  = Op.getOperand(2);
28044     SDValue Mask  = Op.getOperand(3);
28045     SDValue Index = Op.getOperand(4);
28046     SDValue Src   = Op.getOperand(5);
28047     SDValue Scale = Op.getOperand(6);
28048     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
28049                           Scale, Chain, Subtarget);
28050   }
28051   case PREFETCH: {
28052     const APInt &HintVal = Op.getConstantOperandAPInt(6);
28053     assert((HintVal == 2 || HintVal == 3) &&
28054            "Wrong prefetch hint in intrinsic: should be 2 or 3");
28055     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
28056     SDValue Chain = Op.getOperand(0);
28057     SDValue Mask  = Op.getOperand(2);
28058     SDValue Index = Op.getOperand(3);
28059     SDValue Base  = Op.getOperand(4);
28060     SDValue Scale = Op.getOperand(5);
28061     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
28062                            Subtarget);
28063   }
28064   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
28065   case RDTSC: {
28066     SmallVector<SDValue, 2> Results;
28067     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
28068                             Results);
28069     return DAG.getMergeValues(Results, dl);
28070   }
28071   // Read Performance Monitoring Counters.
28072   case RDPMC:
28073   // Read Processor Register.
28074   case RDPRU:
28075   // GetExtended Control Register.
28076   case XGETBV: {
28077     SmallVector<SDValue, 2> Results;
28078 
28079     // RDPMC uses ECX to select the index of the performance counter to read.
28080     // RDPRU uses ECX to select the processor register to read.
28081     // XGETBV uses ECX to select the index of the XCR register to return.
28082     // The result is stored into registers EDX:EAX.
28083     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
28084                                 Subtarget, Results);
28085     return DAG.getMergeValues(Results, dl);
28086   }
28087   // XTEST intrinsics.
28088   case XTEST: {
28089     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
28090     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
28091 
28092     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
28093     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
28094     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
28095                        Ret, SDValue(InTrans.getNode(), 1));
28096   }
28097   case TRUNCATE_TO_MEM_VI8:
28098   case TRUNCATE_TO_MEM_VI16:
28099   case TRUNCATE_TO_MEM_VI32: {
28100     SDValue Mask = Op.getOperand(4);
28101     SDValue DataToTruncate = Op.getOperand(3);
28102     SDValue Addr = Op.getOperand(2);
28103     SDValue Chain = Op.getOperand(0);
28104 
28105     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
28106     assert(MemIntr && "Expected MemIntrinsicSDNode!");
28107 
28108     EVT MemVT  = MemIntr->getMemoryVT();
28109 
28110     uint16_t TruncationOp = IntrData->Opc0;
28111     switch (TruncationOp) {
28112     case X86ISD::VTRUNC: {
28113       if (isAllOnesConstant(Mask)) // return just a truncate store
28114         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
28115                                  MemIntr->getMemOperand());
28116 
28117       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
28118       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
28119       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
28120 
28121       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
28122                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
28123                                 true /* truncating */);
28124     }
28125     case X86ISD::VTRUNCUS:
28126     case X86ISD::VTRUNCS: {
28127       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
28128       if (isAllOnesConstant(Mask))
28129         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
28130                                MemIntr->getMemOperand(), DAG);
28131 
28132       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
28133       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
28134 
28135       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
28136                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
28137     }
28138     default:
28139       llvm_unreachable("Unsupported truncstore intrinsic");
28140     }
28141   }
28142   }
28143 }
28144 
28145 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
28146                                            SelectionDAG &DAG) const {
28147   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
28148   MFI.setReturnAddressIsTaken(true);
28149 
28150   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
28151     return SDValue();
28152 
28153   unsigned Depth = Op.getConstantOperandVal(0);
28154   SDLoc dl(Op);
28155   EVT PtrVT = getPointerTy(DAG.getDataLayout());
28156 
28157   if (Depth > 0) {
28158     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
28159     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
28160     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
28161     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
28162                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
28163                        MachinePointerInfo());
28164   }
28165 
28166   // Just load the return address.
28167   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
28168   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
28169                      MachinePointerInfo());
28170 }
28171 
28172 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
28173                                                  SelectionDAG &DAG) const {
28174   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
28175   return getReturnAddressFrameIndex(DAG);
28176 }
28177 
28178 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
28179   MachineFunction &MF = DAG.getMachineFunction();
28180   MachineFrameInfo &MFI = MF.getFrameInfo();
28181   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
28182   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
28183   EVT VT = Op.getValueType();
28184 
28185   MFI.setFrameAddressIsTaken(true);
28186 
28187   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
28188     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
28189     // is not possible to crawl up the stack without looking at the unwind codes
28190     // simultaneously.
28191     int FrameAddrIndex = FuncInfo->getFAIndex();
28192     if (!FrameAddrIndex) {
28193       // Set up a frame object for the return address.
28194       unsigned SlotSize = RegInfo->getSlotSize();
28195       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
28196           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
28197       FuncInfo->setFAIndex(FrameAddrIndex);
28198     }
28199     return DAG.getFrameIndex(FrameAddrIndex, VT);
28200   }
28201 
28202   unsigned FrameReg =
28203       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
28204   SDLoc dl(Op);  // FIXME probably not meaningful
28205   unsigned Depth = Op.getConstantOperandVal(0);
28206   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
28207           (FrameReg == X86::EBP && VT == MVT::i32)) &&
28208          "Invalid Frame Register!");
28209   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
28210   while (Depth--)
28211     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
28212                             MachinePointerInfo());
28213   return FrameAddr;
28214 }
28215 
28216 // FIXME? Maybe this could be a TableGen attribute on some registers and
28217 // this table could be generated automatically from RegInfo.
28218 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
28219                                               const MachineFunction &MF) const {
28220   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
28221 
28222   Register Reg = StringSwitch<unsigned>(RegName)
28223                        .Case("esp", X86::ESP)
28224                        .Case("rsp", X86::RSP)
28225                        .Case("ebp", X86::EBP)
28226                        .Case("rbp", X86::RBP)
28227                        .Default(0);
28228 
28229   if (Reg == X86::EBP || Reg == X86::RBP) {
28230     if (!TFI.hasFP(MF))
28231       report_fatal_error("register " + StringRef(RegName) +
28232                          " is allocatable: function has no frame pointer");
28233 #ifndef NDEBUG
28234     else {
28235       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
28236       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
28237       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
28238              "Invalid Frame Register!");
28239     }
28240 #endif
28241   }
28242 
28243   if (Reg)
28244     return Reg;
28245 
28246   report_fatal_error("Invalid register name global variable");
28247 }
28248 
28249 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
28250                                                      SelectionDAG &DAG) const {
28251   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
28252   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
28253 }
28254 
28255 Register X86TargetLowering::getExceptionPointerRegister(
28256     const Constant *PersonalityFn) const {
28257   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
28258     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
28259 
28260   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
28261 }
28262 
28263 Register X86TargetLowering::getExceptionSelectorRegister(
28264     const Constant *PersonalityFn) const {
28265   // Funclet personalities don't use selectors (the runtime does the selection).
28266   if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
28267     return X86::NoRegister;
28268   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
28269 }
28270 
28271 bool X86TargetLowering::needsFixedCatchObjects() const {
28272   return Subtarget.isTargetWin64();
28273 }
28274 
28275 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
28276   SDValue Chain     = Op.getOperand(0);
28277   SDValue Offset    = Op.getOperand(1);
28278   SDValue Handler   = Op.getOperand(2);
28279   SDLoc dl      (Op);
28280 
28281   EVT PtrVT = getPointerTy(DAG.getDataLayout());
28282   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
28283   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
28284   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
28285           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
28286          "Invalid Frame Register!");
28287   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
28288   Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
28289 
28290   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
28291                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
28292                                                        dl));
28293   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
28294   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
28295   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
28296 
28297   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
28298                      DAG.getRegister(StoreAddrReg, PtrVT));
28299 }
28300 
28301 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
28302                                                SelectionDAG &DAG) const {
28303   SDLoc DL(Op);
28304   // If the subtarget is not 64bit, we may need the global base reg
28305   // after isel expand pseudo, i.e., after CGBR pass ran.
28306   // Therefore, ask for the GlobalBaseReg now, so that the pass
28307   // inserts the code for us in case we need it.
28308   // Otherwise, we will end up in a situation where we will
28309   // reference a virtual register that is not defined!
28310   if (!Subtarget.is64Bit()) {
28311     const X86InstrInfo *TII = Subtarget.getInstrInfo();
28312     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
28313   }
28314   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
28315                      DAG.getVTList(MVT::i32, MVT::Other),
28316                      Op.getOperand(0), Op.getOperand(1));
28317 }
28318 
28319 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
28320                                                 SelectionDAG &DAG) const {
28321   SDLoc DL(Op);
28322   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
28323                      Op.getOperand(0), Op.getOperand(1));
28324 }
28325 
28326 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
28327                                                        SelectionDAG &DAG) const {
28328   SDLoc DL(Op);
28329   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
28330                      Op.getOperand(0));
28331 }
28332 
28333 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
28334   return Op.getOperand(0);
28335 }
28336 
28337 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
28338                                                 SelectionDAG &DAG) const {
28339   SDValue Root = Op.getOperand(0);
28340   SDValue Trmp = Op.getOperand(1); // trampoline
28341   SDValue FPtr = Op.getOperand(2); // nested function
28342   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
28343   SDLoc dl (Op);
28344 
28345   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
28346   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
28347 
28348   if (Subtarget.is64Bit()) {
28349     SDValue OutChains[6];
28350 
28351     // Large code-model.
28352     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
28353     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
28354 
28355     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
28356     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
28357 
28358     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
28359 
28360     // Load the pointer to the nested function into R11.
28361     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
28362     SDValue Addr = Trmp;
28363     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
28364                                 Addr, MachinePointerInfo(TrmpAddr));
28365 
28366     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
28367                        DAG.getConstant(2, dl, MVT::i64));
28368     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
28369                                 MachinePointerInfo(TrmpAddr, 2), Align(2));
28370 
28371     // Load the 'nest' parameter value into R10.
28372     // R10 is specified in X86CallingConv.td
28373     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
28374     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
28375                        DAG.getConstant(10, dl, MVT::i64));
28376     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
28377                                 Addr, MachinePointerInfo(TrmpAddr, 10));
28378 
28379     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
28380                        DAG.getConstant(12, dl, MVT::i64));
28381     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
28382                                 MachinePointerInfo(TrmpAddr, 12), Align(2));
28383 
28384     // Jump to the nested function.
28385     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
28386     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
28387                        DAG.getConstant(20, dl, MVT::i64));
28388     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
28389                                 Addr, MachinePointerInfo(TrmpAddr, 20));
28390 
28391     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
28392     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
28393                        DAG.getConstant(22, dl, MVT::i64));
28394     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
28395                                 Addr, MachinePointerInfo(TrmpAddr, 22));
28396 
28397     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
28398   } else {
28399     const Function *Func =
28400       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
28401     CallingConv::ID CC = Func->getCallingConv();
28402     unsigned NestReg;
28403 
28404     switch (CC) {
28405     default:
28406       llvm_unreachable("Unsupported calling convention");
28407     case CallingConv::C:
28408     case CallingConv::X86_StdCall: {
28409       // Pass 'nest' parameter in ECX.
28410       // Must be kept in sync with X86CallingConv.td
28411       NestReg = X86::ECX;
28412 
28413       // Check that ECX wasn't needed by an 'inreg' parameter.
28414       FunctionType *FTy = Func->getFunctionType();
28415       const AttributeList &Attrs = Func->getAttributes();
28416 
28417       if (!Attrs.isEmpty() && !Func->isVarArg()) {
28418         unsigned InRegCount = 0;
28419         unsigned Idx = 0;
28420 
28421         for (FunctionType::param_iterator I = FTy->param_begin(),
28422              E = FTy->param_end(); I != E; ++I, ++Idx)
28423           if (Attrs.hasParamAttr(Idx, Attribute::InReg)) {
28424             const DataLayout &DL = DAG.getDataLayout();
28425             // FIXME: should only count parameters that are lowered to integers.
28426             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
28427           }
28428 
28429         if (InRegCount > 2) {
28430           report_fatal_error("Nest register in use - reduce number of inreg"
28431                              " parameters!");
28432         }
28433       }
28434       break;
28435     }
28436     case CallingConv::X86_FastCall:
28437     case CallingConv::X86_ThisCall:
28438     case CallingConv::Fast:
28439     case CallingConv::Tail:
28440     case CallingConv::SwiftTail:
28441       // Pass 'nest' parameter in EAX.
28442       // Must be kept in sync with X86CallingConv.td
28443       NestReg = X86::EAX;
28444       break;
28445     }
28446 
28447     SDValue OutChains[4];
28448     SDValue Addr, Disp;
28449 
28450     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28451                        DAG.getConstant(10, dl, MVT::i32));
28452     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
28453 
28454     // This is storing the opcode for MOV32ri.
28455     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
28456     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
28457     OutChains[0] =
28458         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
28459                      Trmp, MachinePointerInfo(TrmpAddr));
28460 
28461     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28462                        DAG.getConstant(1, dl, MVT::i32));
28463     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
28464                                 MachinePointerInfo(TrmpAddr, 1), Align(1));
28465 
28466     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
28467     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28468                        DAG.getConstant(5, dl, MVT::i32));
28469     OutChains[2] =
28470         DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
28471                      MachinePointerInfo(TrmpAddr, 5), Align(1));
28472 
28473     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28474                        DAG.getConstant(6, dl, MVT::i32));
28475     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
28476                                 MachinePointerInfo(TrmpAddr, 6), Align(1));
28477 
28478     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
28479   }
28480 }
28481 
28482 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
28483                                             SelectionDAG &DAG) const {
28484   /*
28485    The rounding mode is in bits 11:10 of FPSR, and has the following
28486    settings:
28487      00 Round to nearest
28488      01 Round to -inf
28489      10 Round to +inf
28490      11 Round to 0
28491 
28492   FLT_ROUNDS, on the other hand, expects the following:
28493     -1 Undefined
28494      0 Round to 0
28495      1 Round to nearest
28496      2 Round to +inf
28497      3 Round to -inf
28498 
28499   To perform the conversion, we use a packed lookup table of the four 2-bit
28500   values that we can index by FPSP[11:10]
28501     0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
28502 
28503     (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
28504   */
28505 
28506   MachineFunction &MF = DAG.getMachineFunction();
28507   MVT VT = Op.getSimpleValueType();
28508   SDLoc DL(Op);
28509 
28510   // Save FP Control Word to stack slot
28511   int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
28512   SDValue StackSlot =
28513       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
28514 
28515   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
28516 
28517   SDValue Chain = Op.getOperand(0);
28518   SDValue Ops[] = {Chain, StackSlot};
28519   Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
28520                                   DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
28521                                   Align(2), MachineMemOperand::MOStore);
28522 
28523   // Load FP Control Word from stack slot
28524   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
28525   Chain = CWD.getValue(1);
28526 
28527   // Mask and turn the control bits into a shift for the lookup table.
28528   SDValue Shift =
28529     DAG.getNode(ISD::SRL, DL, MVT::i16,
28530                 DAG.getNode(ISD::AND, DL, MVT::i16,
28531                             CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
28532                 DAG.getConstant(9, DL, MVT::i8));
28533   Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
28534 
28535   SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
28536   SDValue RetVal =
28537     DAG.getNode(ISD::AND, DL, MVT::i32,
28538                 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
28539                 DAG.getConstant(3, DL, MVT::i32));
28540 
28541   RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
28542 
28543   return DAG.getMergeValues({RetVal, Chain}, DL);
28544 }
28545 
28546 SDValue X86TargetLowering::LowerSET_ROUNDING(SDValue Op,
28547                                              SelectionDAG &DAG) const {
28548   MachineFunction &MF = DAG.getMachineFunction();
28549   SDLoc DL(Op);
28550   SDValue Chain = Op.getNode()->getOperand(0);
28551 
28552   // FP control word may be set only from data in memory. So we need to allocate
28553   // stack space to save/load FP control word.
28554   int OldCWFrameIdx = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
28555   SDValue StackSlot =
28556       DAG.getFrameIndex(OldCWFrameIdx, getPointerTy(DAG.getDataLayout()));
28557   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, OldCWFrameIdx);
28558   MachineMemOperand *MMO =
28559       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 2, Align(2));
28560 
28561   // Store FP control word into memory.
28562   SDValue Ops[] = {Chain, StackSlot};
28563   Chain = DAG.getMemIntrinsicNode(
28564       X86ISD::FNSTCW16m, DL, DAG.getVTList(MVT::Other), Ops, MVT::i16, MMO);
28565 
28566   // Load FP Control Word from stack slot and clear RM field (bits 11:10).
28567   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI);
28568   Chain = CWD.getValue(1);
28569   CWD = DAG.getNode(ISD::AND, DL, MVT::i16, CWD.getValue(0),
28570                     DAG.getConstant(0xf3ff, DL, MVT::i16));
28571 
28572   // Calculate new rounding mode.
28573   SDValue NewRM = Op.getNode()->getOperand(1);
28574   SDValue RMBits;
28575   if (auto *CVal = dyn_cast<ConstantSDNode>(NewRM)) {
28576     uint64_t RM = CVal->getZExtValue();
28577     int FieldVal;
28578     switch (static_cast<RoundingMode>(RM)) {
28579     case RoundingMode::NearestTiesToEven: FieldVal = X86::rmToNearest; break;
28580     case RoundingMode::TowardNegative:    FieldVal = X86::rmDownward; break;
28581     case RoundingMode::TowardPositive:    FieldVal = X86::rmUpward; break;
28582     case RoundingMode::TowardZero:        FieldVal = X86::rmTowardZero; break;
28583     default:
28584       llvm_unreachable("rounding mode is not supported by X86 hardware");
28585     }
28586     RMBits = DAG.getConstant(FieldVal, DL, MVT::i16);
28587   } else {
28588     // Need to convert argument into bits of control word:
28589     //    0 Round to 0       -> 11
28590     //    1 Round to nearest -> 00
28591     //    2 Round to +inf    -> 10
28592     //    3 Round to -inf    -> 01
28593     // The 2-bit value needs then to be shifted so that it occupies bits 11:10.
28594     // To make the conversion, put all these values into a value 0xc9 and shift
28595     // it left depending on the rounding mode:
28596     //    (0xc9 << 4) & 0xc00 = X86::rmTowardZero
28597     //    (0xc9 << 6) & 0xc00 = X86::rmToNearest
28598     //    ...
28599     // (0xc9 << (2 * NewRM + 4)) & 0xc00
28600     SDValue ShiftValue =
28601         DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
28602                     DAG.getNode(ISD::ADD, DL, MVT::i32,
28603                                 DAG.getNode(ISD::SHL, DL, MVT::i32, NewRM,
28604                                             DAG.getConstant(1, DL, MVT::i8)),
28605                                 DAG.getConstant(4, DL, MVT::i32)));
28606     SDValue Shifted =
28607         DAG.getNode(ISD::SHL, DL, MVT::i16, DAG.getConstant(0xc9, DL, MVT::i16),
28608                     ShiftValue);
28609     RMBits = DAG.getNode(ISD::AND, DL, MVT::i16, Shifted,
28610                          DAG.getConstant(0xc00, DL, MVT::i16));
28611   }
28612 
28613   // Update rounding mode bits and store the new FP Control Word into stack.
28614   CWD = DAG.getNode(ISD::OR, DL, MVT::i16, CWD, RMBits);
28615   Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, /* Alignment = */ 2);
28616 
28617   // Load FP control word from the slot.
28618   SDValue OpsLD[] = {Chain, StackSlot};
28619   MachineMemOperand *MMOL =
28620       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 2, Align(2));
28621   Chain = DAG.getMemIntrinsicNode(
28622       X86ISD::FLDCW16m, DL, DAG.getVTList(MVT::Other), OpsLD, MVT::i16, MMOL);
28623 
28624   // If target supports SSE, set MXCSR as well. Rounding mode is encoded in the
28625   // same way but in bits 14:13.
28626   if (Subtarget.hasSSE1()) {
28627     // Store MXCSR into memory.
28628     Chain = DAG.getNode(
28629         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
28630         DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
28631         StackSlot);
28632 
28633     // Load MXCSR from stack slot and clear RM field (bits 14:13).
28634     SDValue CWD = DAG.getLoad(MVT::i32, DL, Chain, StackSlot, MPI);
28635     Chain = CWD.getValue(1);
28636     CWD = DAG.getNode(ISD::AND, DL, MVT::i32, CWD.getValue(0),
28637                       DAG.getConstant(0xffff9fff, DL, MVT::i32));
28638 
28639     // Shift X87 RM bits from 11:10 to 14:13.
28640     RMBits = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, RMBits);
28641     RMBits = DAG.getNode(ISD::SHL, DL, MVT::i32, RMBits,
28642                          DAG.getConstant(3, DL, MVT::i8));
28643 
28644     // Update rounding mode bits and store the new FP Control Word into stack.
28645     CWD = DAG.getNode(ISD::OR, DL, MVT::i32, CWD, RMBits);
28646     Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, /* Alignment = */ 4);
28647 
28648     // Load MXCSR from the slot.
28649     Chain = DAG.getNode(
28650         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
28651         DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
28652         StackSlot);
28653   }
28654 
28655   return Chain;
28656 }
28657 
28658 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
28659 //
28660 // i8/i16 vector implemented using dword LZCNT vector instruction
28661 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
28662 // split the vector, perform operation on it's Lo a Hi part and
28663 // concatenate the results.
28664 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
28665                                          const X86Subtarget &Subtarget) {
28666   assert(Op.getOpcode() == ISD::CTLZ);
28667   SDLoc dl(Op);
28668   MVT VT = Op.getSimpleValueType();
28669   MVT EltVT = VT.getVectorElementType();
28670   unsigned NumElems = VT.getVectorNumElements();
28671 
28672   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
28673           "Unsupported element type");
28674 
28675   // Split vector, it's Lo and Hi parts will be handled in next iteration.
28676   if (NumElems > 16 ||
28677       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
28678     return splitVectorIntUnary(Op, DAG);
28679 
28680   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
28681   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
28682           "Unsupported value type for operation");
28683 
28684   // Use native supported vector instruction vplzcntd.
28685   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
28686   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
28687   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
28688   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
28689 
28690   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
28691 }
28692 
28693 // Lower CTLZ using a PSHUFB lookup table implementation.
28694 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
28695                                        const X86Subtarget &Subtarget,
28696                                        SelectionDAG &DAG) {
28697   MVT VT = Op.getSimpleValueType();
28698   int NumElts = VT.getVectorNumElements();
28699   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
28700   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
28701 
28702   // Per-nibble leading zero PSHUFB lookup table.
28703   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
28704                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
28705                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
28706                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
28707 
28708   SmallVector<SDValue, 64> LUTVec;
28709   for (int i = 0; i < NumBytes; ++i)
28710     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
28711   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
28712 
28713   // Begin by bitcasting the input to byte vector, then split those bytes
28714   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
28715   // If the hi input nibble is zero then we add both results together, otherwise
28716   // we just take the hi result (by masking the lo result to zero before the
28717   // add).
28718   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
28719   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
28720 
28721   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
28722   SDValue Lo = Op0;
28723   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
28724   SDValue HiZ;
28725   if (CurrVT.is512BitVector()) {
28726     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
28727     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
28728     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
28729   } else {
28730     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
28731   }
28732 
28733   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
28734   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
28735   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
28736   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
28737 
28738   // Merge result back from vXi8 back to VT, working on the lo/hi halves
28739   // of the current vector width in the same way we did for the nibbles.
28740   // If the upper half of the input element is zero then add the halves'
28741   // leading zero counts together, otherwise just use the upper half's.
28742   // Double the width of the result until we are at target width.
28743   while (CurrVT != VT) {
28744     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
28745     int CurrNumElts = CurrVT.getVectorNumElements();
28746     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
28747     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
28748     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
28749 
28750     // Check if the upper half of the input element is zero.
28751     if (CurrVT.is512BitVector()) {
28752       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
28753       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
28754                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
28755       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
28756     } else {
28757       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
28758                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
28759     }
28760     HiZ = DAG.getBitcast(NextVT, HiZ);
28761 
28762     // Move the upper/lower halves to the lower bits as we'll be extending to
28763     // NextVT. Mask the lower result to zero if HiZ is true and add the results
28764     // together.
28765     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
28766     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
28767     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
28768     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
28769     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
28770     CurrVT = NextVT;
28771   }
28772 
28773   return Res;
28774 }
28775 
28776 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
28777                                const X86Subtarget &Subtarget,
28778                                SelectionDAG &DAG) {
28779   MVT VT = Op.getSimpleValueType();
28780 
28781   if (Subtarget.hasCDI() &&
28782       // vXi8 vectors need to be promoted to 512-bits for vXi32.
28783       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
28784     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
28785 
28786   // Decompose 256-bit ops into smaller 128-bit ops.
28787   if (VT.is256BitVector() && !Subtarget.hasInt256())
28788     return splitVectorIntUnary(Op, DAG);
28789 
28790   // Decompose 512-bit ops into smaller 256-bit ops.
28791   if (VT.is512BitVector() && !Subtarget.hasBWI())
28792     return splitVectorIntUnary(Op, DAG);
28793 
28794   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
28795   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
28796 }
28797 
28798 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
28799                          SelectionDAG &DAG) {
28800   MVT VT = Op.getSimpleValueType();
28801   MVT OpVT = VT;
28802   unsigned NumBits = VT.getSizeInBits();
28803   SDLoc dl(Op);
28804   unsigned Opc = Op.getOpcode();
28805 
28806   if (VT.isVector())
28807     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
28808 
28809   Op = Op.getOperand(0);
28810   if (VT == MVT::i8) {
28811     // Zero extend to i32 since there is not an i8 bsr.
28812     OpVT = MVT::i32;
28813     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
28814   }
28815 
28816   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
28817   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
28818   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
28819 
28820   if (Opc == ISD::CTLZ) {
28821     // If src is zero (i.e. bsr sets ZF), returns NumBits.
28822     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
28823                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
28824                      Op.getValue(1)};
28825     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
28826   }
28827 
28828   // Finally xor with NumBits-1.
28829   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
28830                    DAG.getConstant(NumBits - 1, dl, OpVT));
28831 
28832   if (VT == MVT::i8)
28833     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
28834   return Op;
28835 }
28836 
28837 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
28838                          SelectionDAG &DAG) {
28839   MVT VT = Op.getSimpleValueType();
28840   unsigned NumBits = VT.getScalarSizeInBits();
28841   SDValue N0 = Op.getOperand(0);
28842   SDLoc dl(Op);
28843 
28844   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
28845          "Only scalar CTTZ requires custom lowering");
28846 
28847   // Issue a bsf (scan bits forward) which also sets EFLAGS.
28848   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
28849   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
28850 
28851   // If src is zero (i.e. bsf sets ZF), returns NumBits.
28852   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
28853                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
28854                    Op.getValue(1)};
28855   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
28856 }
28857 
28858 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
28859                            const X86Subtarget &Subtarget) {
28860   MVT VT = Op.getSimpleValueType();
28861   if (VT == MVT::i16 || VT == MVT::i32)
28862     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
28863 
28864   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28865     return splitVectorIntBinary(Op, DAG);
28866 
28867   assert(Op.getSimpleValueType().is256BitVector() &&
28868          Op.getSimpleValueType().isInteger() &&
28869          "Only handle AVX 256-bit vector integer operation");
28870   return splitVectorIntBinary(Op, DAG);
28871 }
28872 
28873 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
28874                                   const X86Subtarget &Subtarget) {
28875   MVT VT = Op.getSimpleValueType();
28876   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
28877   unsigned Opcode = Op.getOpcode();
28878   SDLoc DL(Op);
28879 
28880   if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
28881       (VT.is256BitVector() && !Subtarget.hasInt256())) {
28882     assert(Op.getSimpleValueType().isInteger() &&
28883            "Only handle AVX vector integer operation");
28884     return splitVectorIntBinary(Op, DAG);
28885   }
28886 
28887   // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
28888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28889   EVT SetCCResultType =
28890       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28891 
28892   unsigned BitWidth = VT.getScalarSizeInBits();
28893   if (Opcode == ISD::USUBSAT) {
28894     if (!TLI.isOperationLegal(ISD::UMAX, VT) || useVPTERNLOG(Subtarget, VT)) {
28895       // Handle a special-case with a bit-hack instead of cmp+select:
28896       // usubsat X, SMIN --> (X ^ SMIN) & (X s>> BW-1)
28897       // If the target can use VPTERNLOG, DAGToDAG will match this as
28898       // "vpsra + vpternlog" which is better than "vpmax + vpsub" with a
28899       // "broadcast" constant load.
28900       ConstantSDNode *C = isConstOrConstSplat(Y, true);
28901       if (C && C->getAPIntValue().isSignMask()) {
28902         SDValue SignMask = DAG.getConstant(C->getAPIntValue(), DL, VT);
28903         SDValue ShiftAmt = DAG.getConstant(BitWidth - 1, DL, VT);
28904         SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, SignMask);
28905         SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShiftAmt);
28906         return DAG.getNode(ISD::AND, DL, VT, Xor, Sra);
28907       }
28908     }
28909     if (!TLI.isOperationLegal(ISD::UMAX, VT)) {
28910       // usubsat X, Y --> (X >u Y) ? X - Y : 0
28911       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
28912       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
28913       // TODO: Move this to DAGCombiner?
28914       if (SetCCResultType == VT &&
28915           DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
28916         return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
28917       return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
28918     }
28919   }
28920 
28921   if ((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
28922       (!VT.isVector() || VT == MVT::v2i64)) {
28923     APInt MinVal = APInt::getSignedMinValue(BitWidth);
28924     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
28925     SDValue Zero = DAG.getConstant(0, DL, VT);
28926     SDValue Result =
28927         DAG.getNode(Opcode == ISD::SADDSAT ? ISD::SADDO : ISD::SSUBO, DL,
28928                     DAG.getVTList(VT, SetCCResultType), X, Y);
28929     SDValue SumDiff = Result.getValue(0);
28930     SDValue Overflow = Result.getValue(1);
28931     SDValue SatMin = DAG.getConstant(MinVal, DL, VT);
28932     SDValue SatMax = DAG.getConstant(MaxVal, DL, VT);
28933     SDValue SumNeg =
28934         DAG.getSetCC(DL, SetCCResultType, SumDiff, Zero, ISD::SETLT);
28935     Result = DAG.getSelect(DL, VT, SumNeg, SatMax, SatMin);
28936     return DAG.getSelect(DL, VT, Overflow, Result, SumDiff);
28937   }
28938 
28939   // Use default expansion.
28940   return SDValue();
28941 }
28942 
28943 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
28944                         SelectionDAG &DAG) {
28945   MVT VT = Op.getSimpleValueType();
28946   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
28947     // Since X86 does not have CMOV for 8-bit integer, we don't convert
28948     // 8-bit integer abs to NEG and CMOV.
28949     SDLoc DL(Op);
28950     SDValue N0 = Op.getOperand(0);
28951     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
28952                               DAG.getConstant(0, DL, VT), N0);
28953     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_NS, DL, MVT::i8),
28954                      SDValue(Neg.getNode(), 1)};
28955     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
28956   }
28957 
28958   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
28959   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
28960     SDLoc DL(Op);
28961     SDValue Src = Op.getOperand(0);
28962     SDValue Sub =
28963         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
28964     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
28965   }
28966 
28967   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
28968     assert(VT.isInteger() &&
28969            "Only handle AVX 256-bit vector integer operation");
28970     return splitVectorIntUnary(Op, DAG);
28971   }
28972 
28973   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28974     return splitVectorIntUnary(Op, DAG);
28975 
28976   // Default to expand.
28977   return SDValue();
28978 }
28979 
28980 static SDValue LowerAVG(SDValue Op, const X86Subtarget &Subtarget,
28981                         SelectionDAG &DAG) {
28982   MVT VT = Op.getSimpleValueType();
28983 
28984   // For AVX1 cases, split to use legal ops.
28985   if (VT.is256BitVector() && !Subtarget.hasInt256())
28986     return splitVectorIntBinary(Op, DAG);
28987 
28988   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28989     return splitVectorIntBinary(Op, DAG);
28990 
28991   // Default to expand.
28992   return SDValue();
28993 }
28994 
28995 static SDValue LowerMINMAX(SDValue Op, const X86Subtarget &Subtarget,
28996                            SelectionDAG &DAG) {
28997   MVT VT = Op.getSimpleValueType();
28998 
28999   // For AVX1 cases, split to use legal ops.
29000   if (VT.is256BitVector() && !Subtarget.hasInt256())
29001     return splitVectorIntBinary(Op, DAG);
29002 
29003   if (VT == MVT::v32i16 || VT == MVT::v64i8)
29004     return splitVectorIntBinary(Op, DAG);
29005 
29006   // Default to expand.
29007   return SDValue();
29008 }
29009 
29010 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
29011                         SelectionDAG &DAG) {
29012   SDLoc dl(Op);
29013   MVT VT = Op.getSimpleValueType();
29014 
29015   // Decompose 256-bit ops into 128-bit ops.
29016   if (VT.is256BitVector() && !Subtarget.hasInt256())
29017     return splitVectorIntBinary(Op, DAG);
29018 
29019   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
29020     return splitVectorIntBinary(Op, DAG);
29021 
29022   SDValue A = Op.getOperand(0);
29023   SDValue B = Op.getOperand(1);
29024 
29025   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
29026   // vector pairs, multiply and truncate.
29027   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
29028     unsigned NumElts = VT.getVectorNumElements();
29029 
29030     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
29031         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
29032       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
29033       return DAG.getNode(
29034           ISD::TRUNCATE, dl, VT,
29035           DAG.getNode(ISD::MUL, dl, ExVT,
29036                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
29037                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
29038     }
29039 
29040     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29041 
29042     // Extract the lo/hi parts to any extend to i16.
29043     // We're going to mask off the low byte of each result element of the
29044     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
29045     // element.
29046     SDValue Undef = DAG.getUNDEF(VT);
29047     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
29048     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
29049 
29050     SDValue BLo, BHi;
29051     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
29052       // If the RHS is a constant, manually unpackl/unpackh.
29053       SmallVector<SDValue, 16> LoOps, HiOps;
29054       for (unsigned i = 0; i != NumElts; i += 16) {
29055         for (unsigned j = 0; j != 8; ++j) {
29056           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
29057                                                MVT::i16));
29058           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
29059                                                MVT::i16));
29060         }
29061       }
29062 
29063       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
29064       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
29065     } else {
29066       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
29067       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
29068     }
29069 
29070     // Multiply, mask the lower 8bits of the lo/hi results and pack.
29071     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
29072     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
29073     return getPack(DAG, Subtarget, dl, VT, RLo, RHi);
29074   }
29075 
29076   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
29077   if (VT == MVT::v4i32) {
29078     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
29079            "Should not custom lower when pmulld is available!");
29080 
29081     // Extract the odd parts.
29082     static const int UnpackMask[] = { 1, -1, 3, -1 };
29083     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
29084     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
29085 
29086     // Multiply the even parts.
29087     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
29088                                 DAG.getBitcast(MVT::v2i64, A),
29089                                 DAG.getBitcast(MVT::v2i64, B));
29090     // Now multiply odd parts.
29091     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
29092                                DAG.getBitcast(MVT::v2i64, Aodds),
29093                                DAG.getBitcast(MVT::v2i64, Bodds));
29094 
29095     Evens = DAG.getBitcast(VT, Evens);
29096     Odds = DAG.getBitcast(VT, Odds);
29097 
29098     // Merge the two vectors back together with a shuffle. This expands into 2
29099     // shuffles.
29100     static const int ShufMask[] = { 0, 4, 2, 6 };
29101     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
29102   }
29103 
29104   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
29105          "Only know how to lower V2I64/V4I64/V8I64 multiply");
29106   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
29107 
29108   //  Ahi = psrlqi(a, 32);
29109   //  Bhi = psrlqi(b, 32);
29110   //
29111   //  AloBlo = pmuludq(a, b);
29112   //  AloBhi = pmuludq(a, Bhi);
29113   //  AhiBlo = pmuludq(Ahi, b);
29114   //
29115   //  Hi = psllqi(AloBhi + AhiBlo, 32);
29116   //  return AloBlo + Hi;
29117   KnownBits AKnown = DAG.computeKnownBits(A);
29118   KnownBits BKnown = DAG.computeKnownBits(B);
29119 
29120   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
29121   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
29122   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
29123 
29124   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
29125   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
29126   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
29127 
29128   SDValue Zero = DAG.getConstant(0, dl, VT);
29129 
29130   // Only multiply lo/hi halves that aren't known to be zero.
29131   SDValue AloBlo = Zero;
29132   if (!ALoIsZero && !BLoIsZero)
29133     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
29134 
29135   SDValue AloBhi = Zero;
29136   if (!ALoIsZero && !BHiIsZero) {
29137     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
29138     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
29139   }
29140 
29141   SDValue AhiBlo = Zero;
29142   if (!AHiIsZero && !BLoIsZero) {
29143     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
29144     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
29145   }
29146 
29147   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
29148   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
29149 
29150   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
29151 }
29152 
29153 static SDValue LowervXi8MulWithUNPCK(SDValue A, SDValue B, const SDLoc &dl,
29154                                      MVT VT, bool IsSigned,
29155                                      const X86Subtarget &Subtarget,
29156                                      SelectionDAG &DAG,
29157                                      SDValue *Low = nullptr) {
29158   unsigned NumElts = VT.getVectorNumElements();
29159 
29160   // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
29161   // to a vXi16 type. Do the multiplies, shift the results and pack the half
29162   // lane results back together.
29163 
29164   // We'll take different approaches for signed and unsigned.
29165   // For unsigned we'll use punpcklbw/punpckhbw to put zero extend the bytes
29166   // and use pmullw to calculate the full 16-bit product.
29167   // For signed we'll use punpcklbw/punpckbw to extend the bytes to words and
29168   // shift them left into the upper byte of each word. This allows us to use
29169   // pmulhw to calculate the full 16-bit product. This trick means we don't
29170   // need to sign extend the bytes to use pmullw.
29171 
29172   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29173   SDValue Zero = DAG.getConstant(0, dl, VT);
29174 
29175   SDValue ALo, AHi;
29176   if (IsSigned) {
29177     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, A));
29178     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, A));
29179   } else {
29180     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Zero));
29181     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Zero));
29182   }
29183 
29184   SDValue BLo, BHi;
29185   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
29186     // If the RHS is a constant, manually unpackl/unpackh and extend.
29187     SmallVector<SDValue, 16> LoOps, HiOps;
29188     for (unsigned i = 0; i != NumElts; i += 16) {
29189       for (unsigned j = 0; j != 8; ++j) {
29190         SDValue LoOp = B.getOperand(i + j);
29191         SDValue HiOp = B.getOperand(i + j + 8);
29192 
29193         if (IsSigned) {
29194           LoOp = DAG.getAnyExtOrTrunc(LoOp, dl, MVT::i16);
29195           HiOp = DAG.getAnyExtOrTrunc(HiOp, dl, MVT::i16);
29196           LoOp = DAG.getNode(ISD::SHL, dl, MVT::i16, LoOp,
29197                              DAG.getConstant(8, dl, MVT::i16));
29198           HiOp = DAG.getNode(ISD::SHL, dl, MVT::i16, HiOp,
29199                              DAG.getConstant(8, dl, MVT::i16));
29200         } else {
29201           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
29202           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
29203         }
29204 
29205         LoOps.push_back(LoOp);
29206         HiOps.push_back(HiOp);
29207       }
29208     }
29209 
29210     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
29211     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
29212   } else if (IsSigned) {
29213     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, B));
29214     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, B));
29215   } else {
29216     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Zero));
29217     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Zero));
29218   }
29219 
29220   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
29221   // pack back to vXi8.
29222   unsigned MulOpc = IsSigned ? ISD::MULHS : ISD::MUL;
29223   SDValue RLo = DAG.getNode(MulOpc, dl, ExVT, ALo, BLo);
29224   SDValue RHi = DAG.getNode(MulOpc, dl, ExVT, AHi, BHi);
29225 
29226   if (Low)
29227     *Low = getPack(DAG, Subtarget, dl, VT, RLo, RHi);
29228 
29229   return getPack(DAG, Subtarget, dl, VT, RLo, RHi, /*PackHiHalf*/ true);
29230 }
29231 
29232 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
29233                          SelectionDAG &DAG) {
29234   SDLoc dl(Op);
29235   MVT VT = Op.getSimpleValueType();
29236   bool IsSigned = Op->getOpcode() == ISD::MULHS;
29237   unsigned NumElts = VT.getVectorNumElements();
29238   SDValue A = Op.getOperand(0);
29239   SDValue B = Op.getOperand(1);
29240 
29241   // Decompose 256-bit ops into 128-bit ops.
29242   if (VT.is256BitVector() && !Subtarget.hasInt256())
29243     return splitVectorIntBinary(Op, DAG);
29244 
29245   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
29246     return splitVectorIntBinary(Op, DAG);
29247 
29248   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
29249     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
29250            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
29251            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
29252 
29253     // PMULxD operations multiply each even value (starting at 0) of LHS with
29254     // the related value of RHS and produce a widen result.
29255     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
29256     // => <2 x i64> <ae|cg>
29257     //
29258     // In other word, to have all the results, we need to perform two PMULxD:
29259     // 1. one with the even values.
29260     // 2. one with the odd values.
29261     // To achieve #2, with need to place the odd values at an even position.
29262     //
29263     // Place the odd value at an even position (basically, shift all values 1
29264     // step to the left):
29265     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
29266                         9, -1, 11, -1, 13, -1, 15, -1};
29267     // <a|b|c|d> => <b|undef|d|undef>
29268     SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
29269                                         makeArrayRef(&Mask[0], NumElts));
29270     // <e|f|g|h> => <f|undef|h|undef>
29271     SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
29272                                         makeArrayRef(&Mask[0], NumElts));
29273 
29274     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
29275     // ints.
29276     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
29277     unsigned Opcode =
29278         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
29279     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
29280     // => <2 x i64> <ae|cg>
29281     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
29282                                                   DAG.getBitcast(MulVT, A),
29283                                                   DAG.getBitcast(MulVT, B)));
29284     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
29285     // => <2 x i64> <bf|dh>
29286     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
29287                                                   DAG.getBitcast(MulVT, Odd0),
29288                                                   DAG.getBitcast(MulVT, Odd1)));
29289 
29290     // Shuffle it back into the right order.
29291     SmallVector<int, 16> ShufMask(NumElts);
29292     for (int i = 0; i != (int)NumElts; ++i)
29293       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
29294 
29295     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
29296 
29297     // If we have a signed multiply but no PMULDQ fix up the result of an
29298     // unsigned multiply.
29299     if (IsSigned && !Subtarget.hasSSE41()) {
29300       SDValue Zero = DAG.getConstant(0, dl, VT);
29301       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
29302                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
29303       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
29304                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
29305 
29306       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
29307       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
29308     }
29309 
29310     return Res;
29311   }
29312 
29313   // Only i8 vectors should need custom lowering after this.
29314   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
29315          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
29316          "Unsupported vector type");
29317 
29318   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
29319   // logical shift down the upper half and pack back to i8.
29320 
29321   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
29322   // and then ashr/lshr the upper bits down to the lower bits before multiply.
29323 
29324   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
29325       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
29326     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
29327     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
29328     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
29329     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
29330     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
29331     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
29332     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
29333   }
29334 
29335   return LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG);
29336 }
29337 
29338 // Custom lowering for SMULO/UMULO.
29339 static SDValue LowerMULO(SDValue Op, const X86Subtarget &Subtarget,
29340                          SelectionDAG &DAG) {
29341   MVT VT = Op.getSimpleValueType();
29342 
29343   // Scalars defer to LowerXALUO.
29344   if (!VT.isVector())
29345     return LowerXALUO(Op, DAG);
29346 
29347   SDLoc dl(Op);
29348   bool IsSigned = Op->getOpcode() == ISD::SMULO;
29349   SDValue A = Op.getOperand(0);
29350   SDValue B = Op.getOperand(1);
29351   EVT OvfVT = Op->getValueType(1);
29352 
29353   if ((VT == MVT::v32i8 && !Subtarget.hasInt256()) ||
29354       (VT == MVT::v64i8 && !Subtarget.hasBWI())) {
29355     // Extract the LHS Lo/Hi vectors
29356     SDValue LHSLo, LHSHi;
29357     std::tie(LHSLo, LHSHi) = splitVector(A, DAG, dl);
29358 
29359     // Extract the RHS Lo/Hi vectors
29360     SDValue RHSLo, RHSHi;
29361     std::tie(RHSLo, RHSHi) = splitVector(B, DAG, dl);
29362 
29363     EVT LoOvfVT, HiOvfVT;
29364     std::tie(LoOvfVT, HiOvfVT) = DAG.GetSplitDestVTs(OvfVT);
29365     SDVTList LoVTs = DAG.getVTList(LHSLo.getValueType(), LoOvfVT);
29366     SDVTList HiVTs = DAG.getVTList(LHSHi.getValueType(), HiOvfVT);
29367 
29368     // Issue the split operations.
29369     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, LoVTs, LHSLo, RHSLo);
29370     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, HiVTs, LHSHi, RHSHi);
29371 
29372     // Join the separate data results and the overflow results.
29373     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29374     SDValue Ovf = DAG.getNode(ISD::CONCAT_VECTORS, dl, OvfVT, Lo.getValue(1),
29375                               Hi.getValue(1));
29376 
29377     return DAG.getMergeValues({Res, Ovf}, dl);
29378   }
29379 
29380   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29381   EVT SetccVT =
29382       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
29383 
29384   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
29385       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
29386     unsigned NumElts = VT.getVectorNumElements();
29387     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
29388     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
29389     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
29390     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
29391     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
29392 
29393     SDValue Low = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
29394 
29395     SDValue Ovf;
29396     if (IsSigned) {
29397       SDValue High, LowSign;
29398       if (OvfVT.getVectorElementType() == MVT::i1 &&
29399           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
29400         // Rather the truncating try to do the compare on vXi16 or vXi32.
29401         // Shift the high down filling with sign bits.
29402         High = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Mul, 8, DAG);
29403         // Fill all 16 bits with the sign bit from the low.
29404         LowSign =
29405             getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExVT, Mul, 8, DAG);
29406         LowSign = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, LowSign,
29407                                              15, DAG);
29408         SetccVT = OvfVT;
29409         if (!Subtarget.hasBWI()) {
29410           // We can't do a vXi16 compare so sign extend to v16i32.
29411           High = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, High);
29412           LowSign = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, LowSign);
29413         }
29414       } else {
29415         // Otherwise do the compare at vXi8.
29416         High = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
29417         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
29418         LowSign =
29419             DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
29420       }
29421 
29422       Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
29423     } else {
29424       SDValue High =
29425           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
29426       if (OvfVT.getVectorElementType() == MVT::i1 &&
29427           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
29428         // Rather the truncating try to do the compare on vXi16 or vXi32.
29429         SetccVT = OvfVT;
29430         if (!Subtarget.hasBWI()) {
29431           // We can't do a vXi16 compare so sign extend to v16i32.
29432           High = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, High);
29433         }
29434       } else {
29435         // Otherwise do the compare at vXi8.
29436         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
29437       }
29438 
29439       Ovf =
29440           DAG.getSetCC(dl, SetccVT, High,
29441                        DAG.getConstant(0, dl, High.getValueType()), ISD::SETNE);
29442     }
29443 
29444     Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
29445 
29446     return DAG.getMergeValues({Low, Ovf}, dl);
29447   }
29448 
29449   SDValue Low;
29450   SDValue High =
29451       LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG, &Low);
29452 
29453   SDValue Ovf;
29454   if (IsSigned) {
29455     // SMULO overflows if the high bits don't match the sign of the low.
29456     SDValue LowSign =
29457         DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
29458     Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
29459   } else {
29460     // UMULO overflows if the high bits are non-zero.
29461     Ovf =
29462         DAG.getSetCC(dl, SetccVT, High, DAG.getConstant(0, dl, VT), ISD::SETNE);
29463   }
29464 
29465   Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
29466 
29467   return DAG.getMergeValues({Low, Ovf}, dl);
29468 }
29469 
29470 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
29471   assert(Subtarget.isTargetWin64() && "Unexpected target");
29472   EVT VT = Op.getValueType();
29473   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
29474          "Unexpected return type for lowering");
29475 
29476   RTLIB::Libcall LC;
29477   bool isSigned;
29478   switch (Op->getOpcode()) {
29479   default: llvm_unreachable("Unexpected request for libcall!");
29480   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
29481   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
29482   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
29483   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
29484   }
29485 
29486   SDLoc dl(Op);
29487   SDValue InChain = DAG.getEntryNode();
29488 
29489   TargetLowering::ArgListTy Args;
29490   TargetLowering::ArgListEntry Entry;
29491   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
29492     EVT ArgVT = Op->getOperand(i).getValueType();
29493     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
29494            "Unexpected argument type for lowering");
29495     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
29496     int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29497     MachinePointerInfo MPI =
29498         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29499     Entry.Node = StackPtr;
29500     InChain =
29501         DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
29502     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
29503     Entry.Ty = PointerType::get(ArgTy,0);
29504     Entry.IsSExt = false;
29505     Entry.IsZExt = false;
29506     Args.push_back(Entry);
29507   }
29508 
29509   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
29510                                          getPointerTy(DAG.getDataLayout()));
29511 
29512   TargetLowering::CallLoweringInfo CLI(DAG);
29513   CLI.setDebugLoc(dl)
29514       .setChain(InChain)
29515       .setLibCallee(
29516           getLibcallCallingConv(LC),
29517           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
29518           std::move(Args))
29519       .setInRegister()
29520       .setSExtResult(isSigned)
29521       .setZExtResult(!isSigned);
29522 
29523   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
29524   return DAG.getBitcast(VT, CallInfo.first);
29525 }
29526 
29527 SDValue X86TargetLowering::LowerWin64_FP_TO_INT128(SDValue Op,
29528                                                    SelectionDAG &DAG,
29529                                                    SDValue &Chain) const {
29530   assert(Subtarget.isTargetWin64() && "Unexpected target");
29531   EVT VT = Op.getValueType();
29532   bool IsStrict = Op->isStrictFPOpcode();
29533 
29534   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
29535   EVT ArgVT = Arg.getValueType();
29536 
29537   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
29538          "Unexpected return type for lowering");
29539 
29540   RTLIB::Libcall LC;
29541   if (Op->getOpcode() == ISD::FP_TO_SINT ||
29542       Op->getOpcode() == ISD::STRICT_FP_TO_SINT)
29543     LC = RTLIB::getFPTOSINT(ArgVT, VT);
29544   else
29545     LC = RTLIB::getFPTOUINT(ArgVT, VT);
29546   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
29547 
29548   SDLoc dl(Op);
29549   MakeLibCallOptions CallOptions;
29550   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
29551 
29552   SDValue Result;
29553   // Expect the i128 argument returned as a v2i64 in xmm0, cast back to the
29554   // expected VT (i128).
29555   std::tie(Result, Chain) =
29556       makeLibCall(DAG, LC, MVT::v2i64, Arg, CallOptions, dl, Chain);
29557   Result = DAG.getBitcast(VT, Result);
29558   return Result;
29559 }
29560 
29561 SDValue X86TargetLowering::LowerWin64_INT128_TO_FP(SDValue Op,
29562                                                    SelectionDAG &DAG) const {
29563   assert(Subtarget.isTargetWin64() && "Unexpected target");
29564   EVT VT = Op.getValueType();
29565   bool IsStrict = Op->isStrictFPOpcode();
29566 
29567   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
29568   EVT ArgVT = Arg.getValueType();
29569 
29570   assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
29571          "Unexpected argument type for lowering");
29572 
29573   RTLIB::Libcall LC;
29574   if (Op->getOpcode() == ISD::SINT_TO_FP ||
29575       Op->getOpcode() == ISD::STRICT_SINT_TO_FP)
29576     LC = RTLIB::getSINTTOFP(ArgVT, VT);
29577   else
29578     LC = RTLIB::getUINTTOFP(ArgVT, VT);
29579   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
29580 
29581   SDLoc dl(Op);
29582   MakeLibCallOptions CallOptions;
29583   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
29584 
29585   // Pass the i128 argument as an indirect argument on the stack.
29586   SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
29587   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29588   MachinePointerInfo MPI =
29589       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29590   Chain = DAG.getStore(Chain, dl, Arg, StackPtr, MPI, Align(16));
29591 
29592   SDValue Result;
29593   std::tie(Result, Chain) =
29594       makeLibCall(DAG, LC, VT, StackPtr, CallOptions, dl, Chain);
29595   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
29596 }
29597 
29598 // Return true if the required (according to Opcode) shift-imm form is natively
29599 // supported by the Subtarget
29600 static bool supportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
29601                                         unsigned Opcode) {
29602   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
29603     return false;
29604 
29605   if (VT.getScalarSizeInBits() < 16)
29606     return false;
29607 
29608   if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
29609       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
29610     return true;
29611 
29612   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
29613                 (VT.is256BitVector() && Subtarget.hasInt256());
29614 
29615   bool AShift = LShift && (Subtarget.hasAVX512() ||
29616                            (VT != MVT::v2i64 && VT != MVT::v4i64));
29617   return (Opcode == ISD::SRA) ? AShift : LShift;
29618 }
29619 
29620 // The shift amount is a variable, but it is the same for all vector lanes.
29621 // These instructions are defined together with shift-immediate.
29622 static
29623 bool supportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
29624                                       unsigned Opcode) {
29625   return supportedVectorShiftWithImm(VT, Subtarget, Opcode);
29626 }
29627 
29628 // Return true if the required (according to Opcode) variable-shift form is
29629 // natively supported by the Subtarget
29630 static bool supportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
29631                                     unsigned Opcode) {
29632   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
29633     return false;
29634 
29635   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
29636     return false;
29637 
29638   // vXi16 supported only on AVX-512, BWI
29639   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
29640     return false;
29641 
29642   if (Subtarget.hasAVX512() &&
29643       (Subtarget.useAVX512Regs() || !VT.is512BitVector()))
29644     return true;
29645 
29646   bool LShift = VT.is128BitVector() || VT.is256BitVector();
29647   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
29648   return (Opcode == ISD::SRA) ? AShift : LShift;
29649 }
29650 
29651 static SDValue LowerShiftByScalarImmediate(SDValue Op, SelectionDAG &DAG,
29652                                            const X86Subtarget &Subtarget) {
29653   MVT VT = Op.getSimpleValueType();
29654   SDLoc dl(Op);
29655   SDValue R = Op.getOperand(0);
29656   SDValue Amt = Op.getOperand(1);
29657   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
29658 
29659   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
29660     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
29661     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
29662     SDValue Ex = DAG.getBitcast(ExVT, R);
29663 
29664     // ashr(R, 63) === cmp_slt(R, 0)
29665     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
29666       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
29667              "Unsupported PCMPGT op");
29668       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
29669     }
29670 
29671     if (ShiftAmt >= 32) {
29672       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
29673       SDValue Upper =
29674           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
29675       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
29676                                                  ShiftAmt - 32, DAG);
29677       if (VT == MVT::v2i64)
29678         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
29679       if (VT == MVT::v4i64)
29680         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
29681                                   {9, 1, 11, 3, 13, 5, 15, 7});
29682     } else {
29683       // SRA upper i32, SRL whole i64 and select lower i32.
29684       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
29685                                                  ShiftAmt, DAG);
29686       SDValue Lower =
29687           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
29688       Lower = DAG.getBitcast(ExVT, Lower);
29689       if (VT == MVT::v2i64)
29690         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
29691       if (VT == MVT::v4i64)
29692         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
29693                                   {8, 1, 10, 3, 12, 5, 14, 7});
29694     }
29695     return DAG.getBitcast(VT, Ex);
29696   };
29697 
29698   // Optimize shl/srl/sra with constant shift amount.
29699   APInt APIntShiftAmt;
29700   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
29701     return SDValue();
29702 
29703   // If the shift amount is out of range, return undef.
29704   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
29705     return DAG.getUNDEF(VT);
29706 
29707   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
29708 
29709   if (supportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
29710     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
29711 
29712   // i64 SRA needs to be performed as partial shifts.
29713   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
29714        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
29715       Op.getOpcode() == ISD::SRA)
29716     return ArithmeticShiftRight64(ShiftAmt);
29717 
29718   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29719       (Subtarget.hasBWI() && VT == MVT::v64i8)) {
29720     unsigned NumElts = VT.getVectorNumElements();
29721     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29722 
29723     // Simple i8 add case
29724     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
29725       // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
29726       // must be 0). (add undef, undef) however can be any value. To make this
29727       // safe, we must freeze R to ensure that register allocation uses the same
29728       // register for an undefined value. This ensures that the result will
29729       // still be even and preserves the original semantics.
29730       R = DAG.getNode(ISD::FREEZE, dl, VT, R);
29731       return DAG.getNode(ISD::ADD, dl, VT, R, R);
29732     }
29733 
29734     // ashr(R, 7)  === cmp_slt(R, 0)
29735     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
29736       SDValue Zeros = DAG.getConstant(0, dl, VT);
29737       if (VT.is512BitVector()) {
29738         assert(VT == MVT::v64i8 && "Unexpected element type!");
29739         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
29740         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
29741       }
29742       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
29743     }
29744 
29745     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
29746     if (VT == MVT::v16i8 && Subtarget.hasXOP())
29747       return SDValue();
29748 
29749     if (Op.getOpcode() == ISD::SHL) {
29750       // Make a large shift.
29751       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
29752                                                ShiftAmt, DAG);
29753       SHL = DAG.getBitcast(VT, SHL);
29754       // Zero out the rightmost bits.
29755       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
29756       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
29757     }
29758     if (Op.getOpcode() == ISD::SRL) {
29759       // Make a large shift.
29760       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
29761                                                ShiftAmt, DAG);
29762       SRL = DAG.getBitcast(VT, SRL);
29763       // Zero out the leftmost bits.
29764       APInt Mask = APInt::getLowBitsSet(8, 8 - ShiftAmt);
29765       return DAG.getNode(ISD::AND, dl, VT, SRL, DAG.getConstant(Mask, dl, VT));
29766     }
29767     if (Op.getOpcode() == ISD::SRA) {
29768       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
29769       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29770 
29771       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
29772       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
29773       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
29774       return Res;
29775     }
29776     llvm_unreachable("Unknown shift opcode.");
29777   }
29778 
29779   return SDValue();
29780 }
29781 
29782 static SDValue LowerShiftByScalarVariable(SDValue Op, SelectionDAG &DAG,
29783                                           const X86Subtarget &Subtarget) {
29784   MVT VT = Op.getSimpleValueType();
29785   SDLoc dl(Op);
29786   SDValue R = Op.getOperand(0);
29787   SDValue Amt = Op.getOperand(1);
29788   unsigned Opcode = Op.getOpcode();
29789   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
29790 
29791   int BaseShAmtIdx = -1;
29792   if (SDValue BaseShAmt = DAG.getSplatSourceVector(Amt, BaseShAmtIdx)) {
29793     if (supportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode))
29794       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, BaseShAmtIdx,
29795                                  Subtarget, DAG);
29796 
29797     // vXi8 shifts - shift as v8i16 + mask result.
29798     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
29799          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
29800          VT == MVT::v64i8) &&
29801         !Subtarget.hasXOP()) {
29802       unsigned NumElts = VT.getVectorNumElements();
29803       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29804       if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
29805         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
29806         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
29807 
29808         // Create the mask using vXi16 shifts. For shift-rights we need to move
29809         // the upper byte down before splatting the vXi8 mask.
29810         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
29811         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
29812                                       BaseShAmt, BaseShAmtIdx, Subtarget, DAG);
29813         if (Opcode != ISD::SHL)
29814           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
29815                                                8, DAG);
29816         BitMask = DAG.getBitcast(VT, BitMask);
29817         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
29818                                        SmallVector<int, 64>(NumElts, 0));
29819 
29820         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
29821                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
29822                                           BaseShAmtIdx, Subtarget, DAG);
29823         Res = DAG.getBitcast(VT, Res);
29824         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
29825 
29826         if (Opcode == ISD::SRA) {
29827           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
29828           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
29829           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
29830           SignMask =
29831               getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask, BaseShAmt,
29832                                   BaseShAmtIdx, Subtarget, DAG);
29833           SignMask = DAG.getBitcast(VT, SignMask);
29834           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
29835           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
29836         }
29837         return Res;
29838       }
29839     }
29840   }
29841 
29842   return SDValue();
29843 }
29844 
29845 // Convert a shift/rotate left amount to a multiplication scale factor.
29846 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
29847                                        const X86Subtarget &Subtarget,
29848                                        SelectionDAG &DAG) {
29849   MVT VT = Amt.getSimpleValueType();
29850   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
29851         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
29852         (Subtarget.hasAVX512() && VT == MVT::v32i16) ||
29853         (!Subtarget.hasAVX512() && VT == MVT::v16i8) ||
29854         (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29855         (Subtarget.hasBWI() && VT == MVT::v64i8)))
29856     return SDValue();
29857 
29858   MVT SVT = VT.getVectorElementType();
29859   unsigned SVTBits = SVT.getSizeInBits();
29860   unsigned NumElems = VT.getVectorNumElements();
29861 
29862   APInt UndefElts;
29863   SmallVector<APInt> EltBits;
29864   if (getTargetConstantBitsFromNode(Amt, SVTBits, UndefElts, EltBits)) {
29865     APInt One(SVTBits, 1);
29866     SmallVector<SDValue> Elts(NumElems, DAG.getUNDEF(SVT));
29867     for (unsigned I = 0; I != NumElems; ++I) {
29868       if (UndefElts[I] || EltBits[I].uge(SVTBits))
29869         continue;
29870       uint64_t ShAmt = EltBits[I].getZExtValue();
29871       Elts[I] = DAG.getConstant(One.shl(ShAmt), dl, SVT);
29872     }
29873     return DAG.getBuildVector(VT, dl, Elts);
29874   }
29875 
29876   // If the target doesn't support variable shifts, use either FP conversion
29877   // or integer multiplication to avoid shifting each element individually.
29878   if (VT == MVT::v4i32) {
29879     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
29880     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
29881                       DAG.getConstant(0x3f800000U, dl, VT));
29882     Amt = DAG.getBitcast(MVT::v4f32, Amt);
29883     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
29884   }
29885 
29886   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
29887   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
29888     SDValue Z = DAG.getConstant(0, dl, VT);
29889     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
29890     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
29891     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
29892     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
29893     if (Subtarget.hasSSE41())
29894       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
29895     return getPack(DAG, Subtarget, dl, VT, Lo, Hi);
29896   }
29897 
29898   return SDValue();
29899 }
29900 
29901 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
29902                           SelectionDAG &DAG) {
29903   MVT VT = Op.getSimpleValueType();
29904   SDLoc dl(Op);
29905   SDValue R = Op.getOperand(0);
29906   SDValue Amt = Op.getOperand(1);
29907   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29908   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29909 
29910   unsigned Opc = Op.getOpcode();
29911   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
29912   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
29913 
29914   assert(VT.isVector() && "Custom lowering only for vector shifts!");
29915   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
29916 
29917   if (SDValue V = LowerShiftByScalarImmediate(Op, DAG, Subtarget))
29918     return V;
29919 
29920   if (SDValue V = LowerShiftByScalarVariable(Op, DAG, Subtarget))
29921     return V;
29922 
29923   if (supportedVectorVarShift(VT, Subtarget, Opc))
29924     return Op;
29925 
29926   // i64 vector arithmetic shift can be emulated with the transform:
29927   // M = lshr(SIGN_MASK, Amt)
29928   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
29929   if (((VT == MVT::v2i64 && !Subtarget.hasXOP()) ||
29930        (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
29931       Opc == ISD::SRA) {
29932     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
29933     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
29934     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29935     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
29936     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
29937     return R;
29938   }
29939 
29940   // XOP has 128-bit variable logical/arithmetic shifts.
29941   // +ve/-ve Amt = shift left/right.
29942   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
29943                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
29944     if (Opc == ISD::SRL || Opc == ISD::SRA) {
29945       SDValue Zero = DAG.getConstant(0, dl, VT);
29946       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
29947     }
29948     if (Opc == ISD::SHL || Opc == ISD::SRL)
29949       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
29950     if (Opc == ISD::SRA)
29951       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
29952   }
29953 
29954   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
29955   // shifts per-lane and then shuffle the partial results back together.
29956   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
29957     // Splat the shift amounts so the scalar shifts above will catch it.
29958     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
29959     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
29960     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
29961     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
29962     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
29963   }
29964 
29965   // If possible, lower this shift as a sequence of two shifts by
29966   // constant plus a BLENDing shuffle instead of scalarizing it.
29967   // Example:
29968   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
29969   //
29970   // Could be rewritten as:
29971   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
29972   //
29973   // The advantage is that the two shifts from the example would be
29974   // lowered as X86ISD::VSRLI nodes in parallel before blending.
29975   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
29976                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
29977     SDValue Amt1, Amt2;
29978     unsigned NumElts = VT.getVectorNumElements();
29979     SmallVector<int, 8> ShuffleMask;
29980     for (unsigned i = 0; i != NumElts; ++i) {
29981       SDValue A = Amt->getOperand(i);
29982       if (A.isUndef()) {
29983         ShuffleMask.push_back(SM_SentinelUndef);
29984         continue;
29985       }
29986       if (!Amt1 || Amt1 == A) {
29987         ShuffleMask.push_back(i);
29988         Amt1 = A;
29989         continue;
29990       }
29991       if (!Amt2 || Amt2 == A) {
29992         ShuffleMask.push_back(i + NumElts);
29993         Amt2 = A;
29994         continue;
29995       }
29996       break;
29997     }
29998 
29999     // Only perform this blend if we can perform it without loading a mask.
30000     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
30001         (VT != MVT::v16i16 ||
30002          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
30003         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
30004          canWidenShuffleElements(ShuffleMask))) {
30005       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
30006       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
30007       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
30008           Cst2->getAPIntValue().ult(EltSizeInBits)) {
30009         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
30010                                                     Cst1->getZExtValue(), DAG);
30011         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
30012                                                     Cst2->getZExtValue(), DAG);
30013         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
30014       }
30015     }
30016   }
30017 
30018   // If possible, lower this packed shift into a vector multiply instead of
30019   // expanding it into a sequence of scalar shifts.
30020   // For v32i8 cases, it might be quicker to split/extend to vXi16 shifts.
30021   if (Opc == ISD::SHL && !(VT == MVT::v32i8 && (Subtarget.hasXOP() ||
30022                                                 Subtarget.canExtendTo512BW())))
30023     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
30024       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
30025 
30026   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
30027   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
30028   if (Opc == ISD::SRL && ConstantAmt &&
30029       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
30030     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
30031     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
30032     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
30033       SDValue Zero = DAG.getConstant(0, dl, VT);
30034       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
30035       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
30036       return DAG.getSelect(dl, VT, ZAmt, R, Res);
30037     }
30038   }
30039 
30040   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
30041   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
30042   // TODO: Special case handling for shift by 0/1, really we can afford either
30043   // of these cases in pre-SSE41/XOP/AVX512 but not both.
30044   if (Opc == ISD::SRA && ConstantAmt &&
30045       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
30046       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
30047         !Subtarget.hasAVX512()) ||
30048        DAG.isKnownNeverZero(Amt))) {
30049     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
30050     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
30051     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
30052       SDValue Amt0 =
30053           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
30054       SDValue Amt1 =
30055           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
30056       SDValue Sra1 =
30057           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
30058       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
30059       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
30060       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
30061     }
30062   }
30063 
30064   // v4i32 Non Uniform Shifts.
30065   // If the shift amount is constant we can shift each lane using the SSE2
30066   // immediate shifts, else we need to zero-extend each lane to the lower i64
30067   // and shift using the SSE2 variable shifts.
30068   // The separate results can then be blended together.
30069   if (VT == MVT::v4i32) {
30070     SDValue Amt0, Amt1, Amt2, Amt3;
30071     if (ConstantAmt) {
30072       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
30073       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
30074       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
30075       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
30076     } else {
30077       // The SSE2 shifts use the lower i64 as the same shift amount for
30078       // all lanes and the upper i64 is ignored. On AVX we're better off
30079       // just zero-extending, but for SSE just duplicating the top 16-bits is
30080       // cheaper and has the same effect for out of range values.
30081       if (Subtarget.hasAVX()) {
30082         SDValue Z = DAG.getConstant(0, dl, VT);
30083         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
30084         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
30085         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
30086         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
30087       } else {
30088         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
30089         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
30090                                              {4, 5, 6, 7, -1, -1, -1, -1});
30091         SDValue Msk02 = getV4X86ShuffleImm8ForMask({0, 1, 1, 1}, dl, DAG);
30092         SDValue Msk13 = getV4X86ShuffleImm8ForMask({2, 3, 3, 3}, dl, DAG);
30093         Amt0 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk02);
30094         Amt1 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk13);
30095         Amt2 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk02);
30096         Amt3 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk13);
30097       }
30098     }
30099 
30100     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
30101     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
30102     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
30103     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
30104     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
30105 
30106     // Merge the shifted lane results optimally with/without PBLENDW.
30107     // TODO - ideally shuffle combining would handle this.
30108     if (Subtarget.hasSSE41()) {
30109       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
30110       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
30111       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
30112     }
30113     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
30114     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
30115     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
30116   }
30117 
30118   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
30119   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
30120   // make the existing SSE solution better.
30121   // NOTE: We honor prefered vector width before promoting to 512-bits.
30122   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
30123       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
30124       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
30125       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
30126       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
30127     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
30128            "Unexpected vector type");
30129     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
30130     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
30131     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
30132     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
30133     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
30134     return DAG.getNode(ISD::TRUNCATE, dl, VT,
30135                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
30136   }
30137 
30138   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
30139   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
30140   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
30141       (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
30142        (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
30143       !Subtarget.hasXOP()) {
30144     int NumElts = VT.getVectorNumElements();
30145     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
30146 
30147     // Extend constant shift amount to vXi16 (it doesn't matter if the type
30148     // isn't legal).
30149     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
30150     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
30151     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
30152     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
30153     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
30154            "Constant build vector expected");
30155 
30156     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
30157       R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
30158                           : DAG.getZExtOrTrunc(R, dl, ExVT);
30159       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
30160       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
30161       return DAG.getZExtOrTrunc(R, dl, VT);
30162     }
30163 
30164     SmallVector<SDValue, 16> LoAmt, HiAmt;
30165     for (int i = 0; i != NumElts; i += 16) {
30166       for (int j = 0; j != 8; ++j) {
30167         LoAmt.push_back(Amt.getOperand(i + j));
30168         HiAmt.push_back(Amt.getOperand(i + j + 8));
30169       }
30170     }
30171 
30172     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
30173     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
30174     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
30175 
30176     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
30177     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
30178     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
30179     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
30180     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
30181     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
30182     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
30183     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
30184     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
30185   }
30186 
30187   if (VT == MVT::v16i8 ||
30188       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
30189       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
30190     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
30191 
30192     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
30193       if (VT.is512BitVector()) {
30194         // On AVX512BW targets we make use of the fact that VSELECT lowers
30195         // to a masked blend which selects bytes based just on the sign bit
30196         // extracted to a mask.
30197         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
30198         V0 = DAG.getBitcast(VT, V0);
30199         V1 = DAG.getBitcast(VT, V1);
30200         Sel = DAG.getBitcast(VT, Sel);
30201         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
30202                            ISD::SETGT);
30203         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
30204       } else if (Subtarget.hasSSE41()) {
30205         // On SSE41 targets we can use PBLENDVB which selects bytes based just
30206         // on the sign bit.
30207         V0 = DAG.getBitcast(VT, V0);
30208         V1 = DAG.getBitcast(VT, V1);
30209         Sel = DAG.getBitcast(VT, Sel);
30210         return DAG.getBitcast(SelVT,
30211                               DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
30212       }
30213       // On pre-SSE41 targets we test for the sign bit by comparing to
30214       // zero - a negative value will set all bits of the lanes to true
30215       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
30216       SDValue Z = DAG.getConstant(0, dl, SelVT);
30217       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
30218       return DAG.getSelect(dl, SelVT, C, V0, V1);
30219     };
30220 
30221     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
30222     // We can safely do this using i16 shifts as we're only interested in
30223     // the 3 lower bits of each byte.
30224     Amt = DAG.getBitcast(ExtVT, Amt);
30225     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
30226     Amt = DAG.getBitcast(VT, Amt);
30227 
30228     if (Opc == ISD::SHL || Opc == ISD::SRL) {
30229       // r = VSELECT(r, shift(r, 4), a);
30230       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
30231       R = SignBitSelect(VT, Amt, M, R);
30232 
30233       // a += a
30234       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30235 
30236       // r = VSELECT(r, shift(r, 2), a);
30237       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
30238       R = SignBitSelect(VT, Amt, M, R);
30239 
30240       // a += a
30241       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30242 
30243       // return VSELECT(r, shift(r, 1), a);
30244       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
30245       R = SignBitSelect(VT, Amt, M, R);
30246       return R;
30247     }
30248 
30249     if (Opc == ISD::SRA) {
30250       // For SRA we need to unpack each byte to the higher byte of a i16 vector
30251       // so we can correctly sign extend. We don't care what happens to the
30252       // lower byte.
30253       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
30254       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
30255       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
30256       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
30257       ALo = DAG.getBitcast(ExtVT, ALo);
30258       AHi = DAG.getBitcast(ExtVT, AHi);
30259       RLo = DAG.getBitcast(ExtVT, RLo);
30260       RHi = DAG.getBitcast(ExtVT, RHi);
30261 
30262       // r = VSELECT(r, shift(r, 4), a);
30263       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
30264       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
30265       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
30266       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
30267 
30268       // a += a
30269       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
30270       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
30271 
30272       // r = VSELECT(r, shift(r, 2), a);
30273       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
30274       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
30275       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
30276       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
30277 
30278       // a += a
30279       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
30280       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
30281 
30282       // r = VSELECT(r, shift(r, 1), a);
30283       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
30284       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
30285       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
30286       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
30287 
30288       // Logical shift the result back to the lower byte, leaving a zero upper
30289       // byte meaning that we can safely pack with PACKUSWB.
30290       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
30291       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
30292       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
30293     }
30294   }
30295 
30296   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
30297     MVT ExtVT = MVT::v8i32;
30298     SDValue Z = DAG.getConstant(0, dl, VT);
30299     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
30300     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
30301     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
30302     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
30303     ALo = DAG.getBitcast(ExtVT, ALo);
30304     AHi = DAG.getBitcast(ExtVT, AHi);
30305     RLo = DAG.getBitcast(ExtVT, RLo);
30306     RHi = DAG.getBitcast(ExtVT, RHi);
30307     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
30308     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
30309     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
30310     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
30311     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
30312   }
30313 
30314   if (VT == MVT::v8i16) {
30315     // If we have a constant shift amount, the non-SSE41 path is best as
30316     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
30317     bool UseSSE41 = Subtarget.hasSSE41() &&
30318                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
30319 
30320     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
30321       // On SSE41 targets we can use PBLENDVB which selects bytes based just on
30322       // the sign bit.
30323       if (UseSSE41) {
30324         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
30325         V0 = DAG.getBitcast(ExtVT, V0);
30326         V1 = DAG.getBitcast(ExtVT, V1);
30327         Sel = DAG.getBitcast(ExtVT, Sel);
30328         return DAG.getBitcast(
30329             VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
30330       }
30331       // On pre-SSE41 targets we splat the sign bit - a negative value will
30332       // set all bits of the lanes to true and VSELECT uses that in
30333       // its OR(AND(V0,C),AND(V1,~C)) lowering.
30334       SDValue C =
30335           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
30336       return DAG.getSelect(dl, VT, C, V0, V1);
30337     };
30338 
30339     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
30340     if (UseSSE41) {
30341       // On SSE41 targets we need to replicate the shift mask in both
30342       // bytes for PBLENDVB.
30343       Amt = DAG.getNode(
30344           ISD::OR, dl, VT,
30345           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
30346           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
30347     } else {
30348       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
30349     }
30350 
30351     // r = VSELECT(r, shift(r, 8), a);
30352     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
30353     R = SignBitSelect(Amt, M, R);
30354 
30355     // a += a
30356     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30357 
30358     // r = VSELECT(r, shift(r, 4), a);
30359     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
30360     R = SignBitSelect(Amt, M, R);
30361 
30362     // a += a
30363     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30364 
30365     // r = VSELECT(r, shift(r, 2), a);
30366     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
30367     R = SignBitSelect(Amt, M, R);
30368 
30369     // a += a
30370     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30371 
30372     // return VSELECT(r, shift(r, 1), a);
30373     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
30374     R = SignBitSelect(Amt, M, R);
30375     return R;
30376   }
30377 
30378   // Decompose 256-bit shifts into 128-bit shifts.
30379   if (VT.is256BitVector())
30380     return splitVectorIntBinary(Op, DAG);
30381 
30382   if (VT == MVT::v32i16 || VT == MVT::v64i8)
30383     return splitVectorIntBinary(Op, DAG);
30384 
30385   return SDValue();
30386 }
30387 
30388 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
30389                                 SelectionDAG &DAG) {
30390   MVT VT = Op.getSimpleValueType();
30391   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
30392          "Unexpected funnel shift opcode!");
30393 
30394   SDLoc DL(Op);
30395   SDValue Op0 = Op.getOperand(0);
30396   SDValue Op1 = Op.getOperand(1);
30397   SDValue Amt = Op.getOperand(2);
30398   unsigned EltSizeInBits = VT.getScalarSizeInBits();
30399   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
30400 
30401   if (VT.isVector()) {
30402     APInt APIntShiftAmt;
30403     bool IsCstSplat = X86::isConstantSplat(Amt, APIntShiftAmt);
30404 
30405     if (Subtarget.hasVBMI2() && EltSizeInBits > 8) {
30406       if (IsFSHR)
30407         std::swap(Op0, Op1);
30408 
30409       if (IsCstSplat) {
30410         uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
30411         SDValue Imm = DAG.getTargetConstant(ShiftAmt, DL, MVT::i8);
30412         return getAVX512Node(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
30413                              {Op0, Op1, Imm}, DAG, Subtarget);
30414       }
30415       return getAVX512Node(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
30416                            {Op0, Op1, Amt}, DAG, Subtarget);
30417     }
30418     assert((VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8 ||
30419             VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16 ||
30420             VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) &&
30421            "Unexpected funnel shift type!");
30422 
30423     // fshl(x,y,z) -> unpack(y,x) << (z & (bw-1))) >> bw.
30424     // fshr(x,y,z) -> unpack(y,x) >> (z & (bw-1))).
30425     if (IsCstSplat)
30426       return SDValue();
30427 
30428     SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
30429     SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30430     bool IsCst = ISD::isBuildVectorOfConstantSDNodes(AmtMod.getNode());
30431 
30432     // Constant vXi16 funnel shifts can be efficiently handled by default.
30433     if (IsCst && EltSizeInBits == 16)
30434       return SDValue();
30435 
30436     unsigned ShiftOpc = IsFSHR ? ISD::SRL : ISD::SHL;
30437     unsigned NumElts = VT.getVectorNumElements();
30438     MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
30439     MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
30440 
30441     // Split 256-bit integers on XOP/pre-AVX2 targets.
30442     // Split 512-bit integers on non 512-bit BWI targets.
30443     if ((VT.is256BitVector() && ((Subtarget.hasXOP() && EltSizeInBits < 16) ||
30444                                  !Subtarget.hasAVX2())) ||
30445         (VT.is512BitVector() && !Subtarget.useBWIRegs() &&
30446          EltSizeInBits < 32)) {
30447       // Pre-mask the amount modulo using the wider vector.
30448       Op = DAG.getNode(Op.getOpcode(), DL, VT, Op0, Op1, AmtMod);
30449       return splitVectorOp(Op, DAG);
30450     }
30451 
30452     // Attempt to fold scalar shift as unpack(y,x) << zext(splat(z))
30453     if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, ShiftOpc)) {
30454       int ScalarAmtIdx = -1;
30455       if (SDValue ScalarAmt = DAG.getSplatSourceVector(AmtMod, ScalarAmtIdx)) {
30456         // Uniform vXi16 funnel shifts can be efficiently handled by default.
30457         if (EltSizeInBits == 16)
30458           return SDValue();
30459 
30460         SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
30461         SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
30462         Lo = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Lo, ScalarAmt,
30463                                  ScalarAmtIdx, Subtarget, DAG);
30464         Hi = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Hi, ScalarAmt,
30465                                  ScalarAmtIdx, Subtarget, DAG);
30466         return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
30467       }
30468     }
30469 
30470     MVT WideSVT = MVT::getIntegerVT(
30471         std::min<unsigned>(EltSizeInBits * 2, Subtarget.hasBWI() ? 16 : 32));
30472     MVT WideVT = MVT::getVectorVT(WideSVT, NumElts);
30473 
30474     // If per-element shifts are legal, fallback to generic expansion.
30475     if (supportedVectorVarShift(VT, Subtarget, ShiftOpc) || Subtarget.hasXOP())
30476       return SDValue();
30477 
30478     // Attempt to fold as:
30479     // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
30480     // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
30481     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
30482         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
30483       Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Op0);
30484       Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Op1);
30485       AmtMod = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
30486       Op0 = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, Op0,
30487                                        EltSizeInBits, DAG);
30488       SDValue Res = DAG.getNode(ISD::OR, DL, WideVT, Op0, Op1);
30489       Res = DAG.getNode(ShiftOpc, DL, WideVT, Res, AmtMod);
30490       if (!IsFSHR)
30491         Res = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, Res,
30492                                          EltSizeInBits, DAG);
30493       return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
30494     }
30495 
30496     // Attempt to fold per-element (ExtVT) shift as unpack(y,x) << zext(z)
30497     if (((IsCst || !Subtarget.hasAVX512()) && !IsFSHR && EltSizeInBits <= 16) ||
30498         supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc)) {
30499       SDValue Z = DAG.getConstant(0, DL, VT);
30500       SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
30501       SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
30502       SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
30503       SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
30504       SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
30505       SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
30506       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
30507     }
30508 
30509     // Fallback to generic expansion.
30510     return SDValue();
30511   }
30512   assert(
30513       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
30514       "Unexpected funnel shift type!");
30515 
30516   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
30517   bool OptForSize = DAG.shouldOptForSize();
30518   bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
30519 
30520   // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
30521   // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
30522   if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
30523       !isa<ConstantSDNode>(Amt)) {
30524     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
30525     SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
30526     Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
30527     Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
30528     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
30529     SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
30530     Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
30531     if (IsFSHR) {
30532       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
30533     } else {
30534       Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
30535       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
30536     }
30537     return DAG.getZExtOrTrunc(Res, DL, VT);
30538   }
30539 
30540   if (VT == MVT::i8 || ExpandFunnel)
30541     return SDValue();
30542 
30543   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
30544   if (VT == MVT::i16) {
30545     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
30546                       DAG.getConstant(15, DL, Amt.getValueType()));
30547     unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
30548     return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
30549   }
30550 
30551   return Op;
30552 }
30553 
30554 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
30555                            SelectionDAG &DAG) {
30556   MVT VT = Op.getSimpleValueType();
30557   assert(VT.isVector() && "Custom lowering only for vector rotates!");
30558 
30559   SDLoc DL(Op);
30560   SDValue R = Op.getOperand(0);
30561   SDValue Amt = Op.getOperand(1);
30562   unsigned Opcode = Op.getOpcode();
30563   unsigned EltSizeInBits = VT.getScalarSizeInBits();
30564   int NumElts = VT.getVectorNumElements();
30565   bool IsROTL = Opcode == ISD::ROTL;
30566 
30567   // Check for constant splat rotation amount.
30568   APInt CstSplatValue;
30569   bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
30570 
30571   // Check for splat rotate by zero.
30572   if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
30573     return R;
30574 
30575   // AVX512 implicitly uses modulo rotation amounts.
30576   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
30577     // Attempt to rotate by immediate.
30578     if (IsCstSplat) {
30579       unsigned RotOpc = IsROTL ? X86ISD::VROTLI : X86ISD::VROTRI;
30580       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
30581       return DAG.getNode(RotOpc, DL, VT, R,
30582                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
30583     }
30584 
30585     // Else, fall-back on VPROLV/VPRORV.
30586     return Op;
30587   }
30588 
30589   // AVX512 VBMI2 vXi16 - lower to funnel shifts.
30590   if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
30591     unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
30592     return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
30593   }
30594 
30595   SDValue Z = DAG.getConstant(0, DL, VT);
30596 
30597   if (!IsROTL) {
30598     // If the ISD::ROTR amount is constant, we're always better converting to
30599     // ISD::ROTL.
30600     if (SDValue NegAmt = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {Z, Amt}))
30601       return DAG.getNode(ISD::ROTL, DL, VT, R, NegAmt);
30602 
30603     // XOP targets always prefers ISD::ROTL.
30604     if (Subtarget.hasXOP())
30605       return DAG.getNode(ISD::ROTL, DL, VT, R,
30606                          DAG.getNode(ISD::SUB, DL, VT, Z, Amt));
30607   }
30608 
30609   // Split 256-bit integers on XOP/pre-AVX2 targets.
30610   if (VT.is256BitVector() && (Subtarget.hasXOP() || !Subtarget.hasAVX2()))
30611     return splitVectorIntBinary(Op, DAG);
30612 
30613   // XOP has 128-bit vector variable + immediate rotates.
30614   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
30615   // XOP implicitly uses modulo rotation amounts.
30616   if (Subtarget.hasXOP()) {
30617     assert(IsROTL && "Only ROTL expected");
30618     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
30619 
30620     // Attempt to rotate by immediate.
30621     if (IsCstSplat) {
30622       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
30623       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
30624                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
30625     }
30626 
30627     // Use general rotate by variable (per-element).
30628     return Op;
30629   }
30630 
30631   // Rotate by an uniform constant - expand back to shifts.
30632   if (IsCstSplat)
30633     return SDValue();
30634 
30635   // Split 512-bit integers on non 512-bit BWI targets.
30636   if (VT.is512BitVector() && !Subtarget.useBWIRegs())
30637     return splitVectorIntBinary(Op, DAG);
30638 
30639   assert(
30640       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
30641        ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
30642         Subtarget.hasAVX2()) ||
30643        ((VT == MVT::v32i16 || VT == MVT::v64i8) && Subtarget.useBWIRegs())) &&
30644       "Only vXi32/vXi16/vXi8 vector rotates supported");
30645 
30646   MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
30647   MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
30648 
30649   SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
30650   SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30651 
30652   // Attempt to fold as unpack(x,x) << zext(splat(y)):
30653   // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
30654   // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
30655   if (EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) {
30656     int BaseRotAmtIdx = -1;
30657     if (SDValue BaseRotAmt = DAG.getSplatSourceVector(AmtMod, BaseRotAmtIdx)) {
30658       if (EltSizeInBits == 16 && Subtarget.hasSSE41()) {
30659         unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
30660         return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
30661       }
30662       unsigned ShiftX86Opc = IsROTL ? X86ISD::VSHLI : X86ISD::VSRLI;
30663       SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
30664       SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
30665       Lo = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Lo, BaseRotAmt,
30666                                BaseRotAmtIdx, Subtarget, DAG);
30667       Hi = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Hi, BaseRotAmt,
30668                                BaseRotAmtIdx, Subtarget, DAG);
30669       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
30670     }
30671   }
30672 
30673   // v16i8/v32i8/v64i8: Split rotation into rot4/rot2/rot1 stages and select by
30674   // the amount bit.
30675   // TODO: We're doing nothing here that we couldn't do for funnel shifts.
30676   if (EltSizeInBits == 8) {
30677     bool IsConstAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
30678     MVT WideVT =
30679         MVT::getVectorVT(Subtarget.hasBWI() ? MVT::i16 : MVT::i32, NumElts);
30680     unsigned ShiftOpc = IsROTL ? ISD::SHL : ISD::SRL;
30681 
30682     // Attempt to fold as:
30683     // rotl(x,y) -> (((aext(x) << bw) | zext(x)) << (y & (bw-1))) >> bw.
30684     // rotr(x,y) -> (((aext(x) << bw) | zext(x)) >> (y & (bw-1))).
30685     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
30686         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
30687       // If we're rotating by constant, just use default promotion.
30688       if (IsConstAmt)
30689         return SDValue();
30690       // See if we can perform this by widening to vXi16 or vXi32.
30691       R = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, R);
30692       R = DAG.getNode(
30693           ISD::OR, DL, WideVT, R,
30694           getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, R, 8, DAG));
30695       Amt = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
30696       R = DAG.getNode(ShiftOpc, DL, WideVT, R, Amt);
30697       if (IsROTL)
30698         R = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, R, 8, DAG);
30699       return DAG.getNode(ISD::TRUNCATE, DL, VT, R);
30700     }
30701 
30702     // Attempt to fold as unpack(x,x) << zext(y):
30703     // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
30704     // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
30705     if (IsConstAmt || supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc)) {
30706       // See if we can perform this by unpacking to lo/hi vXi16.
30707       SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
30708       SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
30709       SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
30710       SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
30711       SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
30712       SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
30713       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
30714     }
30715     assert((VT == MVT::v16i8 || VT == MVT::v32i8) && "Unsupported vXi8 type");
30716 
30717     // We don't need ModuloAmt here as we just peek at individual bits.
30718     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
30719       if (Subtarget.hasSSE41()) {
30720         // On SSE41 targets we can use PBLENDVB which selects bytes based just
30721         // on the sign bit.
30722         V0 = DAG.getBitcast(VT, V0);
30723         V1 = DAG.getBitcast(VT, V1);
30724         Sel = DAG.getBitcast(VT, Sel);
30725         return DAG.getBitcast(SelVT,
30726                               DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
30727       }
30728       // On pre-SSE41 targets we test for the sign bit by comparing to
30729       // zero - a negative value will set all bits of the lanes to true
30730       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
30731       SDValue Z = DAG.getConstant(0, DL, SelVT);
30732       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
30733       return DAG.getSelect(DL, SelVT, C, V0, V1);
30734     };
30735 
30736     // ISD::ROTR is currently only profitable on AVX512 targets with VPTERNLOG.
30737     if (!IsROTL && !useVPTERNLOG(Subtarget, VT)) {
30738       Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
30739       IsROTL = true;
30740     }
30741 
30742     unsigned ShiftLHS = IsROTL ? ISD::SHL : ISD::SRL;
30743     unsigned ShiftRHS = IsROTL ? ISD::SRL : ISD::SHL;
30744 
30745     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
30746     // We can safely do this using i16 shifts as we're only interested in
30747     // the 3 lower bits of each byte.
30748     Amt = DAG.getBitcast(ExtVT, Amt);
30749     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
30750     Amt = DAG.getBitcast(VT, Amt);
30751 
30752     // r = VSELECT(r, rot(r, 4), a);
30753     SDValue M;
30754     M = DAG.getNode(
30755         ISD::OR, DL, VT,
30756         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(4, DL, VT)),
30757         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(4, DL, VT)));
30758     R = SignBitSelect(VT, Amt, M, R);
30759 
30760     // a += a
30761     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
30762 
30763     // r = VSELECT(r, rot(r, 2), a);
30764     M = DAG.getNode(
30765         ISD::OR, DL, VT,
30766         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(2, DL, VT)),
30767         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(6, DL, VT)));
30768     R = SignBitSelect(VT, Amt, M, R);
30769 
30770     // a += a
30771     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
30772 
30773     // return VSELECT(r, rot(r, 1), a);
30774     M = DAG.getNode(
30775         ISD::OR, DL, VT,
30776         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(1, DL, VT)),
30777         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(7, DL, VT)));
30778     return SignBitSelect(VT, Amt, M, R);
30779   }
30780 
30781   bool IsSplatAmt = DAG.isSplatValue(Amt);
30782   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
30783   bool LegalVarShifts = supportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
30784                         supportedVectorVarShift(VT, Subtarget, ISD::SRL);
30785 
30786   // Fallback for splats + all supported variable shifts.
30787   // Fallback for non-constants AVX2 vXi16 as well.
30788   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
30789     Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30790     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
30791     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
30792     SDValue SHL = DAG.getNode(IsROTL ? ISD::SHL : ISD::SRL, DL, VT, R, Amt);
30793     SDValue SRL = DAG.getNode(IsROTL ? ISD::SRL : ISD::SHL, DL, VT, R, AmtR);
30794     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
30795   }
30796 
30797   // Everything below assumes ISD::ROTL.
30798   if (!IsROTL) {
30799     Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
30800     IsROTL = true;
30801   }
30802 
30803   // ISD::ROT* uses modulo rotate amounts.
30804   Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30805 
30806   assert(IsROTL && "Only ROTL supported");
30807 
30808   // As with shifts, attempt to convert the rotation amount to a multiplication
30809   // factor, fallback to general expansion.
30810   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
30811   if (!Scale)
30812     return SDValue();
30813 
30814   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
30815   if (EltSizeInBits == 16) {
30816     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
30817     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
30818     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
30819   }
30820 
30821   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
30822   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
30823   // that can then be OR'd with the lower 32-bits.
30824   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
30825   static const int OddMask[] = {1, -1, 3, -1};
30826   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
30827   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
30828 
30829   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
30830                               DAG.getBitcast(MVT::v2i64, R),
30831                               DAG.getBitcast(MVT::v2i64, Scale));
30832   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
30833                               DAG.getBitcast(MVT::v2i64, R13),
30834                               DAG.getBitcast(MVT::v2i64, Scale13));
30835   Res02 = DAG.getBitcast(VT, Res02);
30836   Res13 = DAG.getBitcast(VT, Res13);
30837 
30838   return DAG.getNode(ISD::OR, DL, VT,
30839                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
30840                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
30841 }
30842 
30843 /// Returns true if the operand type is exactly twice the native width, and
30844 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
30845 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
30846 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
30847 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
30848   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
30849 
30850   if (OpWidth == 64)
30851     return Subtarget.canUseCMPXCHG8B() && !Subtarget.is64Bit();
30852   if (OpWidth == 128)
30853     return Subtarget.canUseCMPXCHG16B();
30854 
30855   return false;
30856 }
30857 
30858 TargetLoweringBase::AtomicExpansionKind
30859 X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
30860   Type *MemType = SI->getValueOperand()->getType();
30861 
30862   bool NoImplicitFloatOps =
30863       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
30864   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
30865       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
30866       (Subtarget.hasSSE1() || Subtarget.hasX87()))
30867     return AtomicExpansionKind::None;
30868 
30869   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::Expand
30870                                  : AtomicExpansionKind::None;
30871 }
30872 
30873 // Note: this turns large loads into lock cmpxchg8b/16b.
30874 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
30875 TargetLowering::AtomicExpansionKind
30876 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
30877   Type *MemType = LI->getType();
30878 
30879   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
30880   // can use movq to do the load. If we have X87 we can load into an 80-bit
30881   // X87 register and store it to a stack temporary.
30882   bool NoImplicitFloatOps =
30883       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
30884   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
30885       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
30886       (Subtarget.hasSSE1() || Subtarget.hasX87()))
30887     return AtomicExpansionKind::None;
30888 
30889   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
30890                                  : AtomicExpansionKind::None;
30891 }
30892 
30893 TargetLowering::AtomicExpansionKind
30894 X86TargetLowering::shouldExpandLogicAtomicRMWInIR(AtomicRMWInst *AI) const {
30895   // If the atomicrmw's result isn't actually used, we can just add a "lock"
30896   // prefix to a normal instruction for these operations.
30897   if (AI->use_empty())
30898     return AtomicExpansionKind::None;
30899 
30900   // If the atomicrmw's result is used by a single bit AND, we may use
30901   // bts/btr/btc instruction for these operations.
30902   auto *C1 = dyn_cast<ConstantInt>(AI->getValOperand());
30903   Instruction *I = AI->user_back();
30904   if (!C1 || !AI->hasOneUse() || I->getOpcode() != Instruction::And ||
30905       AI->getParent() != I->getParent())
30906     return AtomicExpansionKind::CmpXChg;
30907   // The following instruction must be a AND single bit.
30908   auto *C2 = dyn_cast<ConstantInt>(I->getOperand(1));
30909   unsigned Bits = AI->getType()->getPrimitiveSizeInBits();
30910   if (!C2 || Bits == 8 || !isPowerOf2_64(C2->getZExtValue()))
30911     return AtomicExpansionKind::CmpXChg;
30912 
30913   if (AI->getOperation() == AtomicRMWInst::And)
30914     return ~C1->getValue() == C2->getValue()
30915                ? AtomicExpansionKind::BitTestIntrinsic
30916                : AtomicExpansionKind::CmpXChg;
30917 
30918   return C1 == C2 ? AtomicExpansionKind::BitTestIntrinsic
30919                   : AtomicExpansionKind::CmpXChg;
30920 }
30921 
30922 void X86TargetLowering::emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
30923   IRBuilder<> Builder(AI);
30924   Intrinsic::ID IID = Intrinsic::not_intrinsic;
30925   switch (AI->getOperation()) {
30926   default:
30927     llvm_unreachable("Unknown atomic operation");
30928   case AtomicRMWInst::Or:
30929     IID = Intrinsic::x86_atomic_bts;
30930     break;
30931   case AtomicRMWInst::Xor:
30932     IID = Intrinsic::x86_atomic_btc;
30933     break;
30934   case AtomicRMWInst::And:
30935     IID = Intrinsic::x86_atomic_btr;
30936     break;
30937   }
30938   Instruction *I = AI->user_back();
30939   LLVMContext &Ctx = AI->getContext();
30940   unsigned Imm =
30941       countTrailingZeros(cast<ConstantInt>(I->getOperand(1))->getZExtValue());
30942   Function *BitTest =
30943       Intrinsic::getDeclaration(AI->getModule(), IID, AI->getType());
30944   Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
30945                                           Type::getInt8PtrTy(Ctx));
30946   Value *Result = Builder.CreateCall(BitTest, {Addr, Builder.getInt8(Imm)});
30947   I->replaceAllUsesWith(Result);
30948   I->eraseFromParent();
30949   AI->eraseFromParent();
30950 }
30951 
30952 TargetLowering::AtomicExpansionKind
30953 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
30954   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
30955   Type *MemType = AI->getType();
30956 
30957   // If the operand is too big, we must see if cmpxchg8/16b is available
30958   // and default to library calls otherwise.
30959   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
30960     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
30961                                    : AtomicExpansionKind::None;
30962   }
30963 
30964   AtomicRMWInst::BinOp Op = AI->getOperation();
30965   switch (Op) {
30966   default:
30967     llvm_unreachable("Unknown atomic operation");
30968   case AtomicRMWInst::Xchg:
30969   case AtomicRMWInst::Add:
30970   case AtomicRMWInst::Sub:
30971     // It's better to use xadd, xsub or xchg for these in all cases.
30972     return AtomicExpansionKind::None;
30973   case AtomicRMWInst::Or:
30974   case AtomicRMWInst::And:
30975   case AtomicRMWInst::Xor:
30976     return shouldExpandLogicAtomicRMWInIR(AI);
30977   case AtomicRMWInst::Nand:
30978   case AtomicRMWInst::Max:
30979   case AtomicRMWInst::Min:
30980   case AtomicRMWInst::UMax:
30981   case AtomicRMWInst::UMin:
30982   case AtomicRMWInst::FAdd:
30983   case AtomicRMWInst::FSub:
30984   case AtomicRMWInst::FMax:
30985   case AtomicRMWInst::FMin:
30986     // These always require a non-trivial set of data operations on x86. We must
30987     // use a cmpxchg loop.
30988     return AtomicExpansionKind::CmpXChg;
30989   }
30990 }
30991 
30992 LoadInst *
30993 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
30994   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
30995   Type *MemType = AI->getType();
30996   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
30997   // there is no benefit in turning such RMWs into loads, and it is actually
30998   // harmful as it introduces a mfence.
30999   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
31000     return nullptr;
31001 
31002   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
31003   // lowering available in lowerAtomicArith.
31004   // TODO: push more cases through this path.
31005   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
31006     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
31007         AI->use_empty())
31008       return nullptr;
31009 
31010   IRBuilder<> Builder(AI);
31011   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
31012   auto SSID = AI->getSyncScopeID();
31013   // We must restrict the ordering to avoid generating loads with Release or
31014   // ReleaseAcquire orderings.
31015   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
31016 
31017   // Before the load we need a fence. Here is an example lifted from
31018   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
31019   // is required:
31020   // Thread 0:
31021   //   x.store(1, relaxed);
31022   //   r1 = y.fetch_add(0, release);
31023   // Thread 1:
31024   //   y.fetch_add(42, acquire);
31025   //   r2 = x.load(relaxed);
31026   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
31027   // lowered to just a load without a fence. A mfence flushes the store buffer,
31028   // making the optimization clearly correct.
31029   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
31030   // otherwise, we might be able to be more aggressive on relaxed idempotent
31031   // rmw. In practice, they do not look useful, so we don't try to be
31032   // especially clever.
31033   if (SSID == SyncScope::SingleThread)
31034     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
31035     // the IR level, so we must wrap it in an intrinsic.
31036     return nullptr;
31037 
31038   if (!Subtarget.hasMFence())
31039     // FIXME: it might make sense to use a locked operation here but on a
31040     // different cache-line to prevent cache-line bouncing. In practice it
31041     // is probably a small win, and x86 processors without mfence are rare
31042     // enough that we do not bother.
31043     return nullptr;
31044 
31045   Function *MFence =
31046       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
31047   Builder.CreateCall(MFence, {});
31048 
31049   // Finally we can emit the atomic load.
31050   LoadInst *Loaded = Builder.CreateAlignedLoad(
31051       AI->getType(), AI->getPointerOperand(), AI->getAlign());
31052   Loaded->setAtomic(Order, SSID);
31053   AI->replaceAllUsesWith(Loaded);
31054   AI->eraseFromParent();
31055   return Loaded;
31056 }
31057 
31058 bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
31059   if (!SI.isUnordered())
31060     return false;
31061   return ExperimentalUnorderedISEL;
31062 }
31063 bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
31064   if (!LI.isUnordered())
31065     return false;
31066   return ExperimentalUnorderedISEL;
31067 }
31068 
31069 
31070 /// Emit a locked operation on a stack location which does not change any
31071 /// memory location, but does involve a lock prefix.  Location is chosen to be
31072 /// a) very likely accessed only by a single thread to minimize cache traffic,
31073 /// and b) definitely dereferenceable.  Returns the new Chain result.
31074 static SDValue emitLockedStackOp(SelectionDAG &DAG,
31075                                  const X86Subtarget &Subtarget, SDValue Chain,
31076                                  const SDLoc &DL) {
31077   // Implementation notes:
31078   // 1) LOCK prefix creates a full read/write reordering barrier for memory
31079   // operations issued by the current processor.  As such, the location
31080   // referenced is not relevant for the ordering properties of the instruction.
31081   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
31082   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
31083   // 2) Using an immediate operand appears to be the best encoding choice
31084   // here since it doesn't require an extra register.
31085   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
31086   // is small enough it might just be measurement noise.)
31087   // 4) When choosing offsets, there are several contributing factors:
31088   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
31089   //      line aligned stack object to improve this case.)
31090   //   b) To minimize our chances of introducing a false dependence, we prefer
31091   //      to offset the stack usage from TOS slightly.
31092   //   c) To minimize concerns about cross thread stack usage - in particular,
31093   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
31094   //      captures state in the TOS frame and accesses it from many threads -
31095   //      we want to use an offset such that the offset is in a distinct cache
31096   //      line from the TOS frame.
31097   //
31098   // For a general discussion of the tradeoffs and benchmark results, see:
31099   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
31100 
31101   auto &MF = DAG.getMachineFunction();
31102   auto &TFL = *Subtarget.getFrameLowering();
31103   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
31104 
31105   if (Subtarget.is64Bit()) {
31106     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
31107     SDValue Ops[] = {
31108       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
31109       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
31110       DAG.getRegister(0, MVT::i64),                         // Index
31111       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
31112       DAG.getRegister(0, MVT::i16),                         // Segment.
31113       Zero,
31114       Chain};
31115     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
31116                                      MVT::Other, Ops);
31117     return SDValue(Res, 1);
31118   }
31119 
31120   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
31121   SDValue Ops[] = {
31122     DAG.getRegister(X86::ESP, MVT::i32),            // Base
31123     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
31124     DAG.getRegister(0, MVT::i32),                   // Index
31125     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
31126     DAG.getRegister(0, MVT::i16),                   // Segment.
31127     Zero,
31128     Chain
31129   };
31130   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
31131                                    MVT::Other, Ops);
31132   return SDValue(Res, 1);
31133 }
31134 
31135 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
31136                                  SelectionDAG &DAG) {
31137   SDLoc dl(Op);
31138   AtomicOrdering FenceOrdering =
31139       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
31140   SyncScope::ID FenceSSID =
31141       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
31142 
31143   // The only fence that needs an instruction is a sequentially-consistent
31144   // cross-thread fence.
31145   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
31146       FenceSSID == SyncScope::System) {
31147     if (Subtarget.hasMFence())
31148       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
31149 
31150     SDValue Chain = Op.getOperand(0);
31151     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
31152   }
31153 
31154   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
31155   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
31156 }
31157 
31158 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
31159                              SelectionDAG &DAG) {
31160   MVT T = Op.getSimpleValueType();
31161   SDLoc DL(Op);
31162   unsigned Reg = 0;
31163   unsigned size = 0;
31164   switch(T.SimpleTy) {
31165   default: llvm_unreachable("Invalid value type!");
31166   case MVT::i8:  Reg = X86::AL;  size = 1; break;
31167   case MVT::i16: Reg = X86::AX;  size = 2; break;
31168   case MVT::i32: Reg = X86::EAX; size = 4; break;
31169   case MVT::i64:
31170     assert(Subtarget.is64Bit() && "Node not type legal!");
31171     Reg = X86::RAX; size = 8;
31172     break;
31173   }
31174   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
31175                                   Op.getOperand(2), SDValue());
31176   SDValue Ops[] = { cpIn.getValue(0),
31177                     Op.getOperand(1),
31178                     Op.getOperand(3),
31179                     DAG.getTargetConstant(size, DL, MVT::i8),
31180                     cpIn.getValue(1) };
31181   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
31182   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
31183   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
31184                                            Ops, T, MMO);
31185 
31186   SDValue cpOut =
31187     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
31188   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
31189                                       MVT::i32, cpOut.getValue(2));
31190   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
31191 
31192   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
31193                      cpOut, Success, EFLAGS.getValue(1));
31194 }
31195 
31196 // Create MOVMSKB, taking into account whether we need to split for AVX1.
31197 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
31198                            const X86Subtarget &Subtarget) {
31199   MVT InVT = V.getSimpleValueType();
31200 
31201   if (InVT == MVT::v64i8) {
31202     SDValue Lo, Hi;
31203     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
31204     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
31205     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
31206     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
31207     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
31208     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
31209                      DAG.getConstant(32, DL, MVT::i8));
31210     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
31211   }
31212   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
31213     SDValue Lo, Hi;
31214     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
31215     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
31216     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
31217     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
31218                      DAG.getConstant(16, DL, MVT::i8));
31219     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
31220   }
31221 
31222   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
31223 }
31224 
31225 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
31226                             SelectionDAG &DAG) {
31227   SDValue Src = Op.getOperand(0);
31228   MVT SrcVT = Src.getSimpleValueType();
31229   MVT DstVT = Op.getSimpleValueType();
31230 
31231   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
31232   // half to v32i1 and concatenating the result.
31233   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
31234     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
31235     assert(Subtarget.hasBWI() && "Expected BWI target");
31236     SDLoc dl(Op);
31237     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
31238                              DAG.getIntPtrConstant(0, dl));
31239     Lo = DAG.getBitcast(MVT::v32i1, Lo);
31240     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
31241                              DAG.getIntPtrConstant(1, dl));
31242     Hi = DAG.getBitcast(MVT::v32i1, Hi);
31243     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
31244   }
31245 
31246   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
31247   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
31248     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
31249     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
31250     SDLoc DL(Op);
31251     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
31252     V = getPMOVMSKB(DL, V, DAG, Subtarget);
31253     return DAG.getZExtOrTrunc(V, DL, DstVT);
31254   }
31255 
31256   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
31257           SrcVT == MVT::i64) && "Unexpected VT!");
31258 
31259   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
31260   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
31261       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
31262     // This conversion needs to be expanded.
31263     return SDValue();
31264 
31265   SDLoc dl(Op);
31266   if (SrcVT.isVector()) {
31267     // Widen the vector in input in the case of MVT::v2i32.
31268     // Example: from MVT::v2i32 to MVT::v4i32.
31269     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
31270                                  SrcVT.getVectorNumElements() * 2);
31271     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
31272                       DAG.getUNDEF(SrcVT));
31273   } else {
31274     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
31275            "Unexpected source type in LowerBITCAST");
31276     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
31277   }
31278 
31279   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
31280   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
31281 
31282   if (DstVT == MVT::x86mmx)
31283     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
31284 
31285   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
31286                      DAG.getIntPtrConstant(0, dl));
31287 }
31288 
31289 /// Compute the horizontal sum of bytes in V for the elements of VT.
31290 ///
31291 /// Requires V to be a byte vector and VT to be an integer vector type with
31292 /// wider elements than V's type. The width of the elements of VT determines
31293 /// how many bytes of V are summed horizontally to produce each element of the
31294 /// result.
31295 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
31296                                       const X86Subtarget &Subtarget,
31297                                       SelectionDAG &DAG) {
31298   SDLoc DL(V);
31299   MVT ByteVecVT = V.getSimpleValueType();
31300   MVT EltVT = VT.getVectorElementType();
31301   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
31302          "Expected value to have byte element type.");
31303   assert(EltVT != MVT::i8 &&
31304          "Horizontal byte sum only makes sense for wider elements!");
31305   unsigned VecSize = VT.getSizeInBits();
31306   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
31307 
31308   // PSADBW instruction horizontally add all bytes and leave the result in i64
31309   // chunks, thus directly computes the pop count for v2i64 and v4i64.
31310   if (EltVT == MVT::i64) {
31311     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
31312     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
31313     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
31314     return DAG.getBitcast(VT, V);
31315   }
31316 
31317   if (EltVT == MVT::i32) {
31318     // We unpack the low half and high half into i32s interleaved with zeros so
31319     // that we can use PSADBW to horizontally sum them. The most useful part of
31320     // this is that it lines up the results of two PSADBW instructions to be
31321     // two v2i64 vectors which concatenated are the 4 population counts. We can
31322     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
31323     SDValue Zeros = DAG.getConstant(0, DL, VT);
31324     SDValue V32 = DAG.getBitcast(VT, V);
31325     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
31326     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
31327 
31328     // Do the horizontal sums into two v2i64s.
31329     Zeros = DAG.getConstant(0, DL, ByteVecVT);
31330     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
31331     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
31332                       DAG.getBitcast(ByteVecVT, Low), Zeros);
31333     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
31334                        DAG.getBitcast(ByteVecVT, High), Zeros);
31335 
31336     // Merge them together.
31337     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
31338     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
31339                     DAG.getBitcast(ShortVecVT, Low),
31340                     DAG.getBitcast(ShortVecVT, High));
31341 
31342     return DAG.getBitcast(VT, V);
31343   }
31344 
31345   // The only element type left is i16.
31346   assert(EltVT == MVT::i16 && "Unknown how to handle type");
31347 
31348   // To obtain pop count for each i16 element starting from the pop count for
31349   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
31350   // right by 8. It is important to shift as i16s as i8 vector shift isn't
31351   // directly supported.
31352   SDValue ShifterV = DAG.getConstant(8, DL, VT);
31353   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
31354   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
31355                   DAG.getBitcast(ByteVecVT, V));
31356   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
31357 }
31358 
31359 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
31360                                         const X86Subtarget &Subtarget,
31361                                         SelectionDAG &DAG) {
31362   MVT VT = Op.getSimpleValueType();
31363   MVT EltVT = VT.getVectorElementType();
31364   int NumElts = VT.getVectorNumElements();
31365   (void)EltVT;
31366   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
31367 
31368   // Implement a lookup table in register by using an algorithm based on:
31369   // http://wm.ite.pl/articles/sse-popcount.html
31370   //
31371   // The general idea is that every lower byte nibble in the input vector is an
31372   // index into a in-register pre-computed pop count table. We then split up the
31373   // input vector in two new ones: (1) a vector with only the shifted-right
31374   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
31375   // masked out higher ones) for each byte. PSHUFB is used separately with both
31376   // to index the in-register table. Next, both are added and the result is a
31377   // i8 vector where each element contains the pop count for input byte.
31378   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
31379                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
31380                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
31381                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
31382 
31383   SmallVector<SDValue, 64> LUTVec;
31384   for (int i = 0; i < NumElts; ++i)
31385     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
31386   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
31387   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
31388 
31389   // High nibbles
31390   SDValue FourV = DAG.getConstant(4, DL, VT);
31391   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
31392 
31393   // Low nibbles
31394   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
31395 
31396   // The input vector is used as the shuffle mask that index elements into the
31397   // LUT. After counting low and high nibbles, add the vector to obtain the
31398   // final pop count per i8 element.
31399   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
31400   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
31401   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
31402 }
31403 
31404 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
31405 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
31406 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
31407                                 SelectionDAG &DAG) {
31408   MVT VT = Op.getSimpleValueType();
31409   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
31410          "Unknown CTPOP type to handle");
31411   SDLoc DL(Op.getNode());
31412   SDValue Op0 = Op.getOperand(0);
31413 
31414   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
31415   if (Subtarget.hasVPOPCNTDQ()) {
31416     unsigned NumElems = VT.getVectorNumElements();
31417     assert((VT.getVectorElementType() == MVT::i8 ||
31418             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
31419     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
31420       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
31421       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
31422       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
31423       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
31424     }
31425   }
31426 
31427   // Decompose 256-bit ops into smaller 128-bit ops.
31428   if (VT.is256BitVector() && !Subtarget.hasInt256())
31429     return splitVectorIntUnary(Op, DAG);
31430 
31431   // Decompose 512-bit ops into smaller 256-bit ops.
31432   if (VT.is512BitVector() && !Subtarget.hasBWI())
31433     return splitVectorIntUnary(Op, DAG);
31434 
31435   // For element types greater than i8, do vXi8 pop counts and a bytesum.
31436   if (VT.getScalarType() != MVT::i8) {
31437     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
31438     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
31439     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
31440     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
31441   }
31442 
31443   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
31444   if (!Subtarget.hasSSSE3())
31445     return SDValue();
31446 
31447   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
31448 }
31449 
31450 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
31451                           SelectionDAG &DAG) {
31452   assert(Op.getSimpleValueType().isVector() &&
31453          "We only do custom lowering for vector population count.");
31454   return LowerVectorCTPOP(Op, Subtarget, DAG);
31455 }
31456 
31457 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
31458   MVT VT = Op.getSimpleValueType();
31459   SDValue In = Op.getOperand(0);
31460   SDLoc DL(Op);
31461 
31462   // For scalars, its still beneficial to transfer to/from the SIMD unit to
31463   // perform the BITREVERSE.
31464   if (!VT.isVector()) {
31465     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
31466     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
31467     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
31468     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
31469                        DAG.getIntPtrConstant(0, DL));
31470   }
31471 
31472   int NumElts = VT.getVectorNumElements();
31473   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
31474 
31475   // Decompose 256-bit ops into smaller 128-bit ops.
31476   if (VT.is256BitVector())
31477     return splitVectorIntUnary(Op, DAG);
31478 
31479   assert(VT.is128BitVector() &&
31480          "Only 128-bit vector bitreverse lowering supported.");
31481 
31482   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
31483   // perform the BSWAP in the shuffle.
31484   // Its best to shuffle using the second operand as this will implicitly allow
31485   // memory folding for multiple vectors.
31486   SmallVector<SDValue, 16> MaskElts;
31487   for (int i = 0; i != NumElts; ++i) {
31488     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
31489       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
31490       int PermuteByte = SourceByte | (2 << 5);
31491       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
31492     }
31493   }
31494 
31495   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
31496   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
31497   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
31498                     Res, Mask);
31499   return DAG.getBitcast(VT, Res);
31500 }
31501 
31502 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
31503                                SelectionDAG &DAG) {
31504   MVT VT = Op.getSimpleValueType();
31505 
31506   if (Subtarget.hasXOP() && !VT.is512BitVector())
31507     return LowerBITREVERSE_XOP(Op, DAG);
31508 
31509   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
31510 
31511   SDValue In = Op.getOperand(0);
31512   SDLoc DL(Op);
31513 
31514   assert(VT.getScalarType() == MVT::i8 &&
31515          "Only byte vector BITREVERSE supported");
31516 
31517   // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
31518   if (VT == MVT::v64i8 && !Subtarget.hasBWI())
31519     return splitVectorIntUnary(Op, DAG);
31520 
31521   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
31522   if (VT == MVT::v32i8 && !Subtarget.hasInt256())
31523     return splitVectorIntUnary(Op, DAG);
31524 
31525   unsigned NumElts = VT.getVectorNumElements();
31526 
31527   // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
31528   if (Subtarget.hasGFNI()) {
31529     MVT MatrixVT = MVT::getVectorVT(MVT::i64, NumElts / 8);
31530     SDValue Matrix = DAG.getConstant(0x8040201008040201ULL, DL, MatrixVT);
31531     Matrix = DAG.getBitcast(VT, Matrix);
31532     return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
31533                        DAG.getTargetConstant(0, DL, MVT::i8));
31534   }
31535 
31536   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
31537   // two nibbles and a PSHUFB lookup to find the bitreverse of each
31538   // 0-15 value (moved to the other nibble).
31539   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
31540   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
31541   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
31542 
31543   const int LoLUT[16] = {
31544       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
31545       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
31546       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
31547       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
31548   const int HiLUT[16] = {
31549       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
31550       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
31551       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
31552       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
31553 
31554   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
31555   for (unsigned i = 0; i < NumElts; ++i) {
31556     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
31557     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
31558   }
31559 
31560   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
31561   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
31562   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
31563   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
31564   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
31565 }
31566 
31567 static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
31568                            SelectionDAG &DAG) {
31569   SDLoc DL(Op);
31570   SDValue X = Op.getOperand(0);
31571   MVT VT = Op.getSimpleValueType();
31572 
31573   // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
31574   if (VT == MVT::i8 ||
31575       DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
31576     X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
31577     SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
31578                                 DAG.getConstant(0, DL, MVT::i8));
31579     // Copy the inverse of the parity flag into a register with setcc.
31580     SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
31581     // Extend to the original type.
31582     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
31583   }
31584 
31585   // If we have POPCNT, use the default expansion.
31586   if (Subtarget.hasPOPCNT())
31587     return SDValue();
31588 
31589   if (VT == MVT::i64) {
31590     // Xor the high and low 16-bits together using a 32-bit operation.
31591     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
31592                              DAG.getNode(ISD::SRL, DL, MVT::i64, X,
31593                                          DAG.getConstant(32, DL, MVT::i8)));
31594     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
31595     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
31596   }
31597 
31598   if (VT != MVT::i16) {
31599     // Xor the high and low 16-bits together using a 32-bit operation.
31600     SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
31601                                DAG.getConstant(16, DL, MVT::i8));
31602     X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
31603   } else {
31604     // If the input is 16-bits, we need to extend to use an i32 shift below.
31605     X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
31606   }
31607 
31608   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
31609   // This should allow an h-reg to be used to save a shift.
31610   SDValue Hi = DAG.getNode(
31611       ISD::TRUNCATE, DL, MVT::i8,
31612       DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
31613   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
31614   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
31615   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
31616 
31617   // Copy the inverse of the parity flag into a register with setcc.
31618   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
31619   // Extend to the original type.
31620   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
31621 }
31622 
31623 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
31624                                         const X86Subtarget &Subtarget) {
31625   unsigned NewOpc = 0;
31626   switch (N->getOpcode()) {
31627   case ISD::ATOMIC_LOAD_ADD:
31628     NewOpc = X86ISD::LADD;
31629     break;
31630   case ISD::ATOMIC_LOAD_SUB:
31631     NewOpc = X86ISD::LSUB;
31632     break;
31633   case ISD::ATOMIC_LOAD_OR:
31634     NewOpc = X86ISD::LOR;
31635     break;
31636   case ISD::ATOMIC_LOAD_XOR:
31637     NewOpc = X86ISD::LXOR;
31638     break;
31639   case ISD::ATOMIC_LOAD_AND:
31640     NewOpc = X86ISD::LAND;
31641     break;
31642   default:
31643     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
31644   }
31645 
31646   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
31647 
31648   return DAG.getMemIntrinsicNode(
31649       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
31650       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
31651       /*MemVT=*/N->getSimpleValueType(0), MMO);
31652 }
31653 
31654 /// Lower atomic_load_ops into LOCK-prefixed operations.
31655 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
31656                                 const X86Subtarget &Subtarget) {
31657   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
31658   SDValue Chain = N->getOperand(0);
31659   SDValue LHS = N->getOperand(1);
31660   SDValue RHS = N->getOperand(2);
31661   unsigned Opc = N->getOpcode();
31662   MVT VT = N->getSimpleValueType(0);
31663   SDLoc DL(N);
31664 
31665   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
31666   // can only be lowered when the result is unused.  They should have already
31667   // been transformed into a cmpxchg loop in AtomicExpand.
31668   if (N->hasAnyUseOfValue(0)) {
31669     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
31670     // select LXADD if LOCK_SUB can't be selected.
31671     if (Opc == ISD::ATOMIC_LOAD_SUB) {
31672       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
31673       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
31674                            RHS, AN->getMemOperand());
31675     }
31676     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
31677            "Used AtomicRMW ops other than Add should have been expanded!");
31678     return N;
31679   }
31680 
31681   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
31682   // The core idea here is that since the memory location isn't actually
31683   // changing, all we need is a lowering for the *ordering* impacts of the
31684   // atomicrmw.  As such, we can chose a different operation and memory
31685   // location to minimize impact on other code.
31686   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
31687     // On X86, the only ordering which actually requires an instruction is
31688     // seq_cst which isn't SingleThread, everything just needs to be preserved
31689     // during codegen and then dropped. Note that we expect (but don't assume),
31690     // that orderings other than seq_cst and acq_rel have been canonicalized to
31691     // a store or load.
31692     if (AN->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent &&
31693         AN->getSyncScopeID() == SyncScope::System) {
31694       // Prefer a locked operation against a stack location to minimize cache
31695       // traffic.  This assumes that stack locations are very likely to be
31696       // accessed only by the owning thread.
31697       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
31698       assert(!N->hasAnyUseOfValue(0));
31699       // NOTE: The getUNDEF is needed to give something for the unused result 0.
31700       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
31701                          DAG.getUNDEF(VT), NewChain);
31702     }
31703     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
31704     SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
31705     assert(!N->hasAnyUseOfValue(0));
31706     // NOTE: The getUNDEF is needed to give something for the unused result 0.
31707     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
31708                        DAG.getUNDEF(VT), NewChain);
31709   }
31710 
31711   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
31712   // RAUW the chain, but don't worry about the result, as it's unused.
31713   assert(!N->hasAnyUseOfValue(0));
31714   // NOTE: The getUNDEF is needed to give something for the unused result 0.
31715   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
31716                      DAG.getUNDEF(VT), LockOp.getValue(1));
31717 }
31718 
31719 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
31720                                  const X86Subtarget &Subtarget) {
31721   auto *Node = cast<AtomicSDNode>(Op.getNode());
31722   SDLoc dl(Node);
31723   EVT VT = Node->getMemoryVT();
31724 
31725   bool IsSeqCst =
31726       Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent;
31727   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
31728 
31729   // If this store is not sequentially consistent and the type is legal
31730   // we can just keep it.
31731   if (!IsSeqCst && IsTypeLegal)
31732     return Op;
31733 
31734   if (VT == MVT::i64 && !IsTypeLegal) {
31735     // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
31736     // is enabled.
31737     bool NoImplicitFloatOps =
31738         DAG.getMachineFunction().getFunction().hasFnAttribute(
31739             Attribute::NoImplicitFloat);
31740     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
31741       SDValue Chain;
31742       if (Subtarget.hasSSE1()) {
31743         SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
31744                                        Node->getOperand(2));
31745         MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
31746         SclToVec = DAG.getBitcast(StVT, SclToVec);
31747         SDVTList Tys = DAG.getVTList(MVT::Other);
31748         SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
31749         Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
31750                                         MVT::i64, Node->getMemOperand());
31751       } else if (Subtarget.hasX87()) {
31752         // First load this into an 80-bit X87 register using a stack temporary.
31753         // This will put the whole integer into the significand.
31754         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
31755         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
31756         MachinePointerInfo MPI =
31757             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
31758         Chain =
31759             DAG.getStore(Node->getChain(), dl, Node->getOperand(2), StackPtr,
31760                          MPI, MaybeAlign(), MachineMemOperand::MOStore);
31761         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
31762         SDValue LdOps[] = {Chain, StackPtr};
31763         SDValue Value =
31764             DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
31765                                     /*Align*/ None, MachineMemOperand::MOLoad);
31766         Chain = Value.getValue(1);
31767 
31768         // Now use an FIST to do the atomic store.
31769         SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
31770         Chain =
31771             DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
31772                                     StoreOps, MVT::i64, Node->getMemOperand());
31773       }
31774 
31775       if (Chain) {
31776         // If this is a sequentially consistent store, also emit an appropriate
31777         // barrier.
31778         if (IsSeqCst)
31779           Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
31780 
31781         return Chain;
31782       }
31783     }
31784   }
31785 
31786   // Convert seq_cst store -> xchg
31787   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
31788   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
31789   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
31790                                Node->getMemoryVT(),
31791                                Node->getOperand(0),
31792                                Node->getOperand(1), Node->getOperand(2),
31793                                Node->getMemOperand());
31794   return Swap.getValue(1);
31795 }
31796 
31797 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
31798   SDNode *N = Op.getNode();
31799   MVT VT = N->getSimpleValueType(0);
31800   unsigned Opc = Op.getOpcode();
31801 
31802   // Let legalize expand this if it isn't a legal type yet.
31803   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
31804     return SDValue();
31805 
31806   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
31807   SDLoc DL(N);
31808 
31809   // Set the carry flag.
31810   SDValue Carry = Op.getOperand(2);
31811   EVT CarryVT = Carry.getValueType();
31812   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
31813                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
31814 
31815   bool IsAdd = Opc == ISD::ADDCARRY || Opc == ISD::SADDO_CARRY;
31816   SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
31817                             Op.getOperand(0), Op.getOperand(1),
31818                             Carry.getValue(1));
31819 
31820   bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
31821   SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
31822                            Sum.getValue(1), DL, DAG);
31823   if (N->getValueType(1) == MVT::i1)
31824     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
31825 
31826   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
31827 }
31828 
31829 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
31830                             SelectionDAG &DAG) {
31831   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
31832 
31833   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
31834   // which returns the values as { float, float } (in XMM0) or
31835   // { double, double } (which is returned in XMM0, XMM1).
31836   SDLoc dl(Op);
31837   SDValue Arg = Op.getOperand(0);
31838   EVT ArgVT = Arg.getValueType();
31839   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
31840 
31841   TargetLowering::ArgListTy Args;
31842   TargetLowering::ArgListEntry Entry;
31843 
31844   Entry.Node = Arg;
31845   Entry.Ty = ArgTy;
31846   Entry.IsSExt = false;
31847   Entry.IsZExt = false;
31848   Args.push_back(Entry);
31849 
31850   bool isF64 = ArgVT == MVT::f64;
31851   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
31852   // the small struct {f32, f32} is returned in (eax, edx). For f64,
31853   // the results are returned via SRet in memory.
31854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31855   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
31856   const char *LibcallName = TLI.getLibcallName(LC);
31857   SDValue Callee =
31858       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
31859 
31860   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
31861                       : (Type *)FixedVectorType::get(ArgTy, 4);
31862 
31863   TargetLowering::CallLoweringInfo CLI(DAG);
31864   CLI.setDebugLoc(dl)
31865       .setChain(DAG.getEntryNode())
31866       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
31867 
31868   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
31869 
31870   if (isF64)
31871     // Returned in xmm0 and xmm1.
31872     return CallResult.first;
31873 
31874   // Returned in bits 0:31 and 32:64 xmm0.
31875   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
31876                                CallResult.first, DAG.getIntPtrConstant(0, dl));
31877   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
31878                                CallResult.first, DAG.getIntPtrConstant(1, dl));
31879   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
31880   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
31881 }
31882 
31883 /// Widen a vector input to a vector of NVT.  The
31884 /// input vector must have the same element type as NVT.
31885 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
31886                             bool FillWithZeroes = false) {
31887   // Check if InOp already has the right width.
31888   MVT InVT = InOp.getSimpleValueType();
31889   if (InVT == NVT)
31890     return InOp;
31891 
31892   if (InOp.isUndef())
31893     return DAG.getUNDEF(NVT);
31894 
31895   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
31896          "input and widen element type must match");
31897 
31898   unsigned InNumElts = InVT.getVectorNumElements();
31899   unsigned WidenNumElts = NVT.getVectorNumElements();
31900   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
31901          "Unexpected request for vector widening");
31902 
31903   SDLoc dl(InOp);
31904   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
31905       InOp.getNumOperands() == 2) {
31906     SDValue N1 = InOp.getOperand(1);
31907     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
31908         N1.isUndef()) {
31909       InOp = InOp.getOperand(0);
31910       InVT = InOp.getSimpleValueType();
31911       InNumElts = InVT.getVectorNumElements();
31912     }
31913   }
31914   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
31915       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
31916     SmallVector<SDValue, 16> Ops;
31917     for (unsigned i = 0; i < InNumElts; ++i)
31918       Ops.push_back(InOp.getOperand(i));
31919 
31920     EVT EltVT = InOp.getOperand(0).getValueType();
31921 
31922     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
31923       DAG.getUNDEF(EltVT);
31924     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
31925       Ops.push_back(FillVal);
31926     return DAG.getBuildVector(NVT, dl, Ops);
31927   }
31928   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
31929     DAG.getUNDEF(NVT);
31930   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
31931                      InOp, DAG.getIntPtrConstant(0, dl));
31932 }
31933 
31934 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
31935                              SelectionDAG &DAG) {
31936   assert(Subtarget.hasAVX512() &&
31937          "MGATHER/MSCATTER are supported on AVX-512 arch only");
31938 
31939   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
31940   SDValue Src = N->getValue();
31941   MVT VT = Src.getSimpleValueType();
31942   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
31943   SDLoc dl(Op);
31944 
31945   SDValue Scale = N->getScale();
31946   SDValue Index = N->getIndex();
31947   SDValue Mask = N->getMask();
31948   SDValue Chain = N->getChain();
31949   SDValue BasePtr = N->getBasePtr();
31950 
31951   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
31952     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
31953     // If the index is v2i64 and we have VLX we can use xmm for data and index.
31954     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
31955       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31956       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
31957       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
31958       SDVTList VTs = DAG.getVTList(MVT::Other);
31959       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
31960       return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
31961                                      N->getMemoryVT(), N->getMemOperand());
31962     }
31963     return SDValue();
31964   }
31965 
31966   MVT IndexVT = Index.getSimpleValueType();
31967 
31968   // If the index is v2i32, we're being called by type legalization and we
31969   // should just let the default handling take care of it.
31970   if (IndexVT == MVT::v2i32)
31971     return SDValue();
31972 
31973   // If we don't have VLX and neither the passthru or index is 512-bits, we
31974   // need to widen until one is.
31975   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
31976       !Index.getSimpleValueType().is512BitVector()) {
31977     // Determine how much we need to widen by to get a 512-bit type.
31978     unsigned Factor = std::min(512/VT.getSizeInBits(),
31979                                512/IndexVT.getSizeInBits());
31980     unsigned NumElts = VT.getVectorNumElements() * Factor;
31981 
31982     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
31983     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
31984     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
31985 
31986     Src = ExtendToType(Src, VT, DAG);
31987     Index = ExtendToType(Index, IndexVT, DAG);
31988     Mask = ExtendToType(Mask, MaskVT, DAG, true);
31989   }
31990 
31991   SDVTList VTs = DAG.getVTList(MVT::Other);
31992   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
31993   return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
31994                                  N->getMemoryVT(), N->getMemOperand());
31995 }
31996 
31997 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
31998                           SelectionDAG &DAG) {
31999 
32000   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
32001   MVT VT = Op.getSimpleValueType();
32002   MVT ScalarVT = VT.getScalarType();
32003   SDValue Mask = N->getMask();
32004   MVT MaskVT = Mask.getSimpleValueType();
32005   SDValue PassThru = N->getPassThru();
32006   SDLoc dl(Op);
32007 
32008   // Handle AVX masked loads which don't support passthru other than 0.
32009   if (MaskVT.getVectorElementType() != MVT::i1) {
32010     // We also allow undef in the isel pattern.
32011     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
32012       return Op;
32013 
32014     SDValue NewLoad = DAG.getMaskedLoad(
32015         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
32016         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
32017         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
32018         N->isExpandingLoad());
32019     // Emit a blend.
32020     SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
32021     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
32022   }
32023 
32024   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
32025          "Expanding masked load is supported on AVX-512 target only!");
32026 
32027   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
32028          "Expanding masked load is supported for 32 and 64-bit types only!");
32029 
32030   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
32031          "Cannot lower masked load op.");
32032 
32033   assert((ScalarVT.getSizeInBits() >= 32 ||
32034           (Subtarget.hasBWI() &&
32035               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
32036          "Unsupported masked load op.");
32037 
32038   // This operation is legal for targets with VLX, but without
32039   // VLX the vector should be widened to 512 bit
32040   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
32041   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
32042   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
32043 
32044   // Mask element has to be i1.
32045   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
32046          "Unexpected mask type");
32047 
32048   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
32049 
32050   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
32051   SDValue NewLoad = DAG.getMaskedLoad(
32052       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
32053       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
32054       N->getExtensionType(), N->isExpandingLoad());
32055 
32056   SDValue Extract =
32057       DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
32058                   DAG.getIntPtrConstant(0, dl));
32059   SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
32060   return DAG.getMergeValues(RetOps, dl);
32061 }
32062 
32063 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
32064                            SelectionDAG &DAG) {
32065   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
32066   SDValue DataToStore = N->getValue();
32067   MVT VT = DataToStore.getSimpleValueType();
32068   MVT ScalarVT = VT.getScalarType();
32069   SDValue Mask = N->getMask();
32070   SDLoc dl(Op);
32071 
32072   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
32073          "Expanding masked load is supported on AVX-512 target only!");
32074 
32075   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
32076          "Expanding masked load is supported for 32 and 64-bit types only!");
32077 
32078   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
32079          "Cannot lower masked store op.");
32080 
32081   assert((ScalarVT.getSizeInBits() >= 32 ||
32082           (Subtarget.hasBWI() &&
32083               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
32084           "Unsupported masked store op.");
32085 
32086   // This operation is legal for targets with VLX, but without
32087   // VLX the vector should be widened to 512 bit
32088   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
32089   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
32090 
32091   // Mask element has to be i1.
32092   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
32093          "Unexpected mask type");
32094 
32095   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
32096 
32097   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
32098   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
32099   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
32100                             N->getOffset(), Mask, N->getMemoryVT(),
32101                             N->getMemOperand(), N->getAddressingMode(),
32102                             N->isTruncatingStore(), N->isCompressingStore());
32103 }
32104 
32105 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
32106                             SelectionDAG &DAG) {
32107   assert(Subtarget.hasAVX2() &&
32108          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
32109 
32110   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
32111   SDLoc dl(Op);
32112   MVT VT = Op.getSimpleValueType();
32113   SDValue Index = N->getIndex();
32114   SDValue Mask = N->getMask();
32115   SDValue PassThru = N->getPassThru();
32116   MVT IndexVT = Index.getSimpleValueType();
32117 
32118   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
32119 
32120   // If the index is v2i32, we're being called by type legalization.
32121   if (IndexVT == MVT::v2i32)
32122     return SDValue();
32123 
32124   // If we don't have VLX and neither the passthru or index is 512-bits, we
32125   // need to widen until one is.
32126   MVT OrigVT = VT;
32127   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
32128       !IndexVT.is512BitVector()) {
32129     // Determine how much we need to widen by to get a 512-bit type.
32130     unsigned Factor = std::min(512/VT.getSizeInBits(),
32131                                512/IndexVT.getSizeInBits());
32132 
32133     unsigned NumElts = VT.getVectorNumElements() * Factor;
32134 
32135     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
32136     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
32137     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
32138 
32139     PassThru = ExtendToType(PassThru, VT, DAG);
32140     Index = ExtendToType(Index, IndexVT, DAG);
32141     Mask = ExtendToType(Mask, MaskVT, DAG, true);
32142   }
32143 
32144   // Break dependency on the data register.
32145   if (PassThru.isUndef())
32146     PassThru = getZeroVector(VT, Subtarget, DAG, dl);
32147 
32148   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
32149                     N->getScale() };
32150   SDValue NewGather = DAG.getMemIntrinsicNode(
32151       X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
32152       N->getMemOperand());
32153   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
32154                                 NewGather, DAG.getIntPtrConstant(0, dl));
32155   return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
32156 }
32157 
32158 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
32159   SDLoc dl(Op);
32160   SDValue Src = Op.getOperand(0);
32161   MVT DstVT = Op.getSimpleValueType();
32162 
32163   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
32164   unsigned SrcAS = N->getSrcAddressSpace();
32165 
32166   assert(SrcAS != N->getDestAddressSpace() &&
32167          "addrspacecast must be between different address spaces");
32168 
32169   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
32170     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
32171   } else if (DstVT == MVT::i64) {
32172     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
32173   } else if (DstVT == MVT::i32) {
32174     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
32175   } else {
32176     report_fatal_error("Bad address space in addrspacecast");
32177   }
32178   return Op;
32179 }
32180 
32181 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
32182                                               SelectionDAG &DAG) const {
32183   // TODO: Eventually, the lowering of these nodes should be informed by or
32184   // deferred to the GC strategy for the function in which they appear. For
32185   // now, however, they must be lowered to something. Since they are logically
32186   // no-ops in the case of a null GC strategy (or a GC strategy which does not
32187   // require special handling for these nodes), lower them as literal NOOPs for
32188   // the time being.
32189   SmallVector<SDValue, 2> Ops;
32190   Ops.push_back(Op.getOperand(0));
32191   if (Op->getGluedNode())
32192     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
32193 
32194   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
32195   return SDValue(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
32196 }
32197 
32198 // Custom split CVTPS2PH with wide types.
32199 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
32200   SDLoc dl(Op);
32201   EVT VT = Op.getValueType();
32202   SDValue Lo, Hi;
32203   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
32204   EVT LoVT, HiVT;
32205   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
32206   SDValue RC = Op.getOperand(1);
32207   Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
32208   Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
32209   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32210 }
32211 
32212 /// Provide custom lowering hooks for some operations.
32213 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
32214   switch (Op.getOpcode()) {
32215   default: llvm_unreachable("Should not custom lower this!");
32216   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
32217   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
32218     return LowerCMP_SWAP(Op, Subtarget, DAG);
32219   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
32220   case ISD::ATOMIC_LOAD_ADD:
32221   case ISD::ATOMIC_LOAD_SUB:
32222   case ISD::ATOMIC_LOAD_OR:
32223   case ISD::ATOMIC_LOAD_XOR:
32224   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
32225   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
32226   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
32227   case ISD::PARITY:             return LowerPARITY(Op, Subtarget, DAG);
32228   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
32229   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
32230   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
32231   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
32232   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
32233   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
32234   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
32235   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
32236   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
32237   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
32238   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
32239   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
32240   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
32241   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
32242   case ISD::SHL_PARTS:
32243   case ISD::SRA_PARTS:
32244   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
32245   case ISD::FSHL:
32246   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
32247   case ISD::STRICT_SINT_TO_FP:
32248   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
32249   case ISD::STRICT_UINT_TO_FP:
32250   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
32251   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
32252   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
32253   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
32254   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
32255   case ISD::ZERO_EXTEND_VECTOR_INREG:
32256   case ISD::SIGN_EXTEND_VECTOR_INREG:
32257     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
32258   case ISD::FP_TO_SINT:
32259   case ISD::STRICT_FP_TO_SINT:
32260   case ISD::FP_TO_UINT:
32261   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
32262   case ISD::FP_TO_SINT_SAT:
32263   case ISD::FP_TO_UINT_SAT:     return LowerFP_TO_INT_SAT(Op, DAG);
32264   case ISD::FP_EXTEND:
32265   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
32266   case ISD::FP_ROUND:
32267   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
32268   case ISD::FP16_TO_FP:
32269   case ISD::STRICT_FP16_TO_FP:  return LowerFP16_TO_FP(Op, DAG);
32270   case ISD::FP_TO_FP16:
32271   case ISD::STRICT_FP_TO_FP16:  return LowerFP_TO_FP16(Op, DAG);
32272   case ISD::FP_TO_BF16:         return LowerFP_TO_BF16(Op, DAG);
32273   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
32274   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
32275   case ISD::FADD:
32276   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
32277   case ISD::FROUND:             return LowerFROUND(Op, DAG);
32278   case ISD::FABS:
32279   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
32280   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
32281   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
32282   case ISD::LRINT:
32283   case ISD::LLRINT:             return LowerLRINT_LLRINT(Op, DAG);
32284   case ISD::SETCC:
32285   case ISD::STRICT_FSETCC:
32286   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
32287   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
32288   case ISD::SELECT:             return LowerSELECT(Op, DAG);
32289   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
32290   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
32291   case ISD::VASTART:            return LowerVASTART(Op, DAG);
32292   case ISD::VAARG:              return LowerVAARG(Op, DAG);
32293   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
32294   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
32295   case ISD::INTRINSIC_VOID:
32296   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
32297   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
32298   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
32299   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
32300   case ISD::FRAME_TO_ARGS_OFFSET:
32301                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
32302   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
32303   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
32304   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
32305   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
32306   case ISD::EH_SJLJ_SETUP_DISPATCH:
32307     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
32308   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
32309   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
32310   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
32311   case ISD::SET_ROUNDING:       return LowerSET_ROUNDING(Op, DAG);
32312   case ISD::CTLZ:
32313   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
32314   case ISD::CTTZ:
32315   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
32316   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
32317   case ISD::MULHS:
32318   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
32319   case ISD::ROTL:
32320   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
32321   case ISD::SRA:
32322   case ISD::SRL:
32323   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
32324   case ISD::SADDO:
32325   case ISD::UADDO:
32326   case ISD::SSUBO:
32327   case ISD::USUBO:              return LowerXALUO(Op, DAG);
32328   case ISD::SMULO:
32329   case ISD::UMULO:              return LowerMULO(Op, Subtarget, DAG);
32330   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
32331   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
32332   case ISD::SADDO_CARRY:
32333   case ISD::SSUBO_CARRY:
32334   case ISD::ADDCARRY:
32335   case ISD::SUBCARRY:           return LowerADDSUBCARRY(Op, DAG);
32336   case ISD::ADD:
32337   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
32338   case ISD::UADDSAT:
32339   case ISD::SADDSAT:
32340   case ISD::USUBSAT:
32341   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
32342   case ISD::SMAX:
32343   case ISD::SMIN:
32344   case ISD::UMAX:
32345   case ISD::UMIN:               return LowerMINMAX(Op, Subtarget, DAG);
32346   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
32347   case ISD::AVGCEILU:           return LowerAVG(Op, Subtarget, DAG);
32348   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
32349   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
32350   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
32351   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
32352   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
32353   case ISD::GC_TRANSITION_START:
32354   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
32355   case ISD::ADDRSPACECAST:      return LowerADDRSPACECAST(Op, DAG);
32356   case X86ISD::CVTPS2PH:        return LowerCVTPS2PH(Op, DAG);
32357   }
32358 }
32359 
32360 /// Replace a node with an illegal result type with a new node built out of
32361 /// custom code.
32362 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
32363                                            SmallVectorImpl<SDValue>&Results,
32364                                            SelectionDAG &DAG) const {
32365   SDLoc dl(N);
32366   switch (N->getOpcode()) {
32367   default:
32368 #ifndef NDEBUG
32369     dbgs() << "ReplaceNodeResults: ";
32370     N->dump(&DAG);
32371 #endif
32372     llvm_unreachable("Do not know how to custom type legalize this operation!");
32373   case X86ISD::CVTPH2PS: {
32374     EVT VT = N->getValueType(0);
32375     SDValue Lo, Hi;
32376     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
32377     EVT LoVT, HiVT;
32378     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
32379     Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
32380     Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
32381     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32382     Results.push_back(Res);
32383     return;
32384   }
32385   case X86ISD::STRICT_CVTPH2PS: {
32386     EVT VT = N->getValueType(0);
32387     SDValue Lo, Hi;
32388     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
32389     EVT LoVT, HiVT;
32390     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
32391     Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
32392                      {N->getOperand(0), Lo});
32393     Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
32394                      {N->getOperand(0), Hi});
32395     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
32396                                 Lo.getValue(1), Hi.getValue(1));
32397     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32398     Results.push_back(Res);
32399     Results.push_back(Chain);
32400     return;
32401   }
32402   case X86ISD::CVTPS2PH:
32403     Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
32404     return;
32405   case ISD::CTPOP: {
32406     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
32407     // Use a v2i64 if possible.
32408     bool NoImplicitFloatOps =
32409         DAG.getMachineFunction().getFunction().hasFnAttribute(
32410             Attribute::NoImplicitFloat);
32411     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
32412       SDValue Wide =
32413           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
32414       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
32415       // Bit count should fit in 32-bits, extract it as that and then zero
32416       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
32417       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
32418       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
32419                          DAG.getIntPtrConstant(0, dl));
32420       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
32421       Results.push_back(Wide);
32422     }
32423     return;
32424   }
32425   case ISD::MUL: {
32426     EVT VT = N->getValueType(0);
32427     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32428            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
32429     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
32430     // elements are needed.
32431     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
32432     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
32433     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
32434     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
32435     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
32436     unsigned NumConcats = 16 / VT.getVectorNumElements();
32437     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
32438     ConcatOps[0] = Res;
32439     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
32440     Results.push_back(Res);
32441     return;
32442   }
32443   case ISD::SMULO:
32444   case ISD::UMULO: {
32445     EVT VT = N->getValueType(0);
32446     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32447            VT == MVT::v2i32 && "Unexpected VT!");
32448     bool IsSigned = N->getOpcode() == ISD::SMULO;
32449     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
32450     SDValue Op0 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(0));
32451     SDValue Op1 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(1));
32452     SDValue Res = DAG.getNode(ISD::MUL, dl, MVT::v2i64, Op0, Op1);
32453     // Extract the high 32 bits from each result using PSHUFD.
32454     // TODO: Could use SRL+TRUNCATE but that doesn't become a PSHUFD.
32455     SDValue Hi = DAG.getBitcast(MVT::v4i32, Res);
32456     Hi = DAG.getVectorShuffle(MVT::v4i32, dl, Hi, Hi, {1, 3, -1, -1});
32457     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Hi,
32458                      DAG.getIntPtrConstant(0, dl));
32459 
32460     // Truncate the low bits of the result. This will become PSHUFD.
32461     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
32462 
32463     SDValue HiCmp;
32464     if (IsSigned) {
32465       // SMULO overflows if the high bits don't match the sign of the low.
32466       HiCmp = DAG.getNode(ISD::SRA, dl, VT, Res, DAG.getConstant(31, dl, VT));
32467     } else {
32468       // UMULO overflows if the high bits are non-zero.
32469       HiCmp = DAG.getConstant(0, dl, VT);
32470     }
32471     SDValue Ovf = DAG.getSetCC(dl, N->getValueType(1), Hi, HiCmp, ISD::SETNE);
32472 
32473     // Widen the result with by padding with undef.
32474     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
32475                       DAG.getUNDEF(VT));
32476     Results.push_back(Res);
32477     Results.push_back(Ovf);
32478     return;
32479   }
32480   case X86ISD::VPMADDWD: {
32481     // Legalize types for X86ISD::VPMADDWD by widening.
32482     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32483 
32484     EVT VT = N->getValueType(0);
32485     EVT InVT = N->getOperand(0).getValueType();
32486     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
32487            "Expected a VT that divides into 128 bits.");
32488     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32489            "Unexpected type action!");
32490     unsigned NumConcat = 128 / InVT.getSizeInBits();
32491 
32492     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
32493                                     InVT.getVectorElementType(),
32494                                     NumConcat * InVT.getVectorNumElements());
32495     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
32496                                   VT.getVectorElementType(),
32497                                   NumConcat * VT.getVectorNumElements());
32498 
32499     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
32500     Ops[0] = N->getOperand(0);
32501     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
32502     Ops[0] = N->getOperand(1);
32503     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
32504 
32505     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
32506     Results.push_back(Res);
32507     return;
32508   }
32509   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
32510   case X86ISD::FMINC:
32511   case X86ISD::FMIN:
32512   case X86ISD::FMAXC:
32513   case X86ISD::FMAX: {
32514     EVT VT = N->getValueType(0);
32515     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
32516     SDValue UNDEF = DAG.getUNDEF(VT);
32517     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
32518                               N->getOperand(0), UNDEF);
32519     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
32520                               N->getOperand(1), UNDEF);
32521     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
32522     return;
32523   }
32524   case ISD::SDIV:
32525   case ISD::UDIV:
32526   case ISD::SREM:
32527   case ISD::UREM: {
32528     EVT VT = N->getValueType(0);
32529     if (VT.isVector()) {
32530       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32531              "Unexpected type action!");
32532       // If this RHS is a constant splat vector we can widen this and let
32533       // division/remainder by constant optimize it.
32534       // TODO: Can we do something for non-splat?
32535       APInt SplatVal;
32536       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
32537         unsigned NumConcats = 128 / VT.getSizeInBits();
32538         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
32539         Ops0[0] = N->getOperand(0);
32540         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
32541         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
32542         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
32543         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
32544         Results.push_back(Res);
32545       }
32546       return;
32547     }
32548 
32549     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
32550     Results.push_back(V);
32551     return;
32552   }
32553   case ISD::TRUNCATE: {
32554     MVT VT = N->getSimpleValueType(0);
32555     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
32556       return;
32557 
32558     // The generic legalizer will try to widen the input type to the same
32559     // number of elements as the widened result type. But this isn't always
32560     // the best thing so do some custom legalization to avoid some cases.
32561     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
32562     SDValue In = N->getOperand(0);
32563     EVT InVT = In.getValueType();
32564 
32565     unsigned InBits = InVT.getSizeInBits();
32566     if (128 % InBits == 0) {
32567       // 128 bit and smaller inputs should avoid truncate all together and
32568       // just use a build_vector that will become a shuffle.
32569       // TODO: Widen and use a shuffle directly?
32570       MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
32571       EVT EltVT = VT.getVectorElementType();
32572       unsigned WidenNumElts = WidenVT.getVectorNumElements();
32573       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
32574       // Use the original element count so we don't do more scalar opts than
32575       // necessary.
32576       unsigned MinElts = VT.getVectorNumElements();
32577       for (unsigned i=0; i < MinElts; ++i) {
32578         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
32579                                   DAG.getIntPtrConstant(i, dl));
32580         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
32581       }
32582       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
32583       return;
32584     }
32585     // With AVX512 there are some cases that can use a target specific
32586     // truncate node to go from 256/512 to less than 128 with zeros in the
32587     // upper elements of the 128 bit result.
32588     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
32589       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
32590       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
32591         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
32592         return;
32593       }
32594       // There's one case we can widen to 512 bits and use VTRUNC.
32595       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
32596         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
32597                          DAG.getUNDEF(MVT::v4i64));
32598         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
32599         return;
32600       }
32601     }
32602     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
32603         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
32604         isTypeLegal(MVT::v4i64)) {
32605       // Input needs to be split and output needs to widened. Let's use two
32606       // VTRUNCs, and shuffle their results together into the wider type.
32607       SDValue Lo, Hi;
32608       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
32609 
32610       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
32611       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
32612       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
32613                                          { 0,  1,  2,  3, 16, 17, 18, 19,
32614                                           -1, -1, -1, -1, -1, -1, -1, -1 });
32615       Results.push_back(Res);
32616       return;
32617     }
32618 
32619     return;
32620   }
32621   case ISD::ANY_EXTEND:
32622     // Right now, only MVT::v8i8 has Custom action for an illegal type.
32623     // It's intended to custom handle the input type.
32624     assert(N->getValueType(0) == MVT::v8i8 &&
32625            "Do not know how to legalize this Node");
32626     return;
32627   case ISD::SIGN_EXTEND:
32628   case ISD::ZERO_EXTEND: {
32629     EVT VT = N->getValueType(0);
32630     SDValue In = N->getOperand(0);
32631     EVT InVT = In.getValueType();
32632     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
32633         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
32634       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
32635              "Unexpected type action!");
32636       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
32637       // Custom split this so we can extend i8/i16->i32 invec. This is better
32638       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
32639       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
32640       // we allow the sra from the extend to i32 to be shared by the split.
32641       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
32642 
32643       // Fill a vector with sign bits for each element.
32644       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
32645       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
32646 
32647       // Create an unpackl and unpackh to interleave the sign bits then bitcast
32648       // to v2i64.
32649       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
32650                                         {0, 4, 1, 5});
32651       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
32652       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
32653                                         {2, 6, 3, 7});
32654       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
32655 
32656       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32657       Results.push_back(Res);
32658       return;
32659     }
32660 
32661     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
32662       if (!InVT.is128BitVector()) {
32663         // Not a 128 bit vector, but maybe type legalization will promote
32664         // it to 128 bits.
32665         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
32666           return;
32667         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
32668         if (!InVT.is128BitVector())
32669           return;
32670 
32671         // Promote the input to 128 bits. Type legalization will turn this into
32672         // zext_inreg/sext_inreg.
32673         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
32674       }
32675 
32676       // Perform custom splitting instead of the two stage extend we would get
32677       // by default.
32678       EVT LoVT, HiVT;
32679       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
32680       assert(isTypeLegal(LoVT) && "Split VT not legal?");
32681 
32682       SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
32683 
32684       // We need to shift the input over by half the number of elements.
32685       unsigned NumElts = InVT.getVectorNumElements();
32686       unsigned HalfNumElts = NumElts / 2;
32687       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
32688       for (unsigned i = 0; i != HalfNumElts; ++i)
32689         ShufMask[i] = i + HalfNumElts;
32690 
32691       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
32692       Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
32693 
32694       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32695       Results.push_back(Res);
32696     }
32697     return;
32698   }
32699   case ISD::FP_TO_SINT:
32700   case ISD::STRICT_FP_TO_SINT:
32701   case ISD::FP_TO_UINT:
32702   case ISD::STRICT_FP_TO_UINT: {
32703     bool IsStrict = N->isStrictFPOpcode();
32704     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
32705                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
32706     EVT VT = N->getValueType(0);
32707     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32708     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
32709     EVT SrcVT = Src.getValueType();
32710 
32711     SDValue Res;
32712     if (isSoftFP16(SrcVT)) {
32713       EVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
32714       if (IsStrict) {
32715         Res =
32716             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
32717                         {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
32718                                             {NVT, MVT::Other}, {Chain, Src})});
32719         Chain = Res.getValue(1);
32720       } else {
32721         Res = DAG.getNode(N->getOpcode(), dl, VT,
32722                           DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
32723       }
32724       Results.push_back(Res);
32725       if (IsStrict)
32726         Results.push_back(Chain);
32727 
32728       return;
32729     }
32730 
32731     if (VT.isVector() && Subtarget.hasFP16() &&
32732         SrcVT.getVectorElementType() == MVT::f16) {
32733       EVT EleVT = VT.getVectorElementType();
32734       EVT ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
32735 
32736       if (SrcVT != MVT::v8f16) {
32737         SDValue Tmp =
32738             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
32739         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
32740         Ops[0] = Src;
32741         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
32742       }
32743 
32744       if (IsStrict) {
32745         unsigned Opc =
32746             IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32747         Res =
32748             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {N->getOperand(0), Src});
32749         Chain = Res.getValue(1);
32750       } else {
32751         unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32752         Res = DAG.getNode(Opc, dl, ResVT, Src);
32753       }
32754 
32755       // TODO: Need to add exception check code for strict FP.
32756       if (EleVT.getSizeInBits() < 16) {
32757         MVT TmpVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8);
32758         Res = DAG.getNode(ISD::TRUNCATE, dl, TmpVT, Res);
32759 
32760         // Now widen to 128 bits.
32761         unsigned NumConcats = 128 / TmpVT.getSizeInBits();
32762         MVT ConcatVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8 * NumConcats);
32763         SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(TmpVT));
32764         ConcatOps[0] = Res;
32765         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
32766       }
32767 
32768       Results.push_back(Res);
32769       if (IsStrict)
32770         Results.push_back(Chain);
32771 
32772       return;
32773     }
32774 
32775     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
32776       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32777              "Unexpected type action!");
32778 
32779       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
32780       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
32781       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
32782                                        VT.getVectorNumElements());
32783       SDValue Res;
32784       SDValue Chain;
32785       if (IsStrict) {
32786         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
32787                           {N->getOperand(0), Src});
32788         Chain = Res.getValue(1);
32789       } else
32790         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
32791 
32792       // Preserve what we know about the size of the original result. If the
32793       // result is v2i32, we have to manually widen the assert.
32794       if (PromoteVT == MVT::v2i32)
32795         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
32796                           DAG.getUNDEF(MVT::v2i32));
32797 
32798       Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext, dl,
32799                         Res.getValueType(), Res,
32800                         DAG.getValueType(VT.getVectorElementType()));
32801 
32802       if (PromoteVT == MVT::v2i32)
32803         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
32804                           DAG.getIntPtrConstant(0, dl));
32805 
32806       // Truncate back to the original width.
32807       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
32808 
32809       // Now widen to 128 bits.
32810       unsigned NumConcats = 128 / VT.getSizeInBits();
32811       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
32812                                       VT.getVectorNumElements() * NumConcats);
32813       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
32814       ConcatOps[0] = Res;
32815       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
32816       Results.push_back(Res);
32817       if (IsStrict)
32818         Results.push_back(Chain);
32819       return;
32820     }
32821 
32822 
32823     if (VT == MVT::v2i32) {
32824       assert((!IsStrict || IsSigned || Subtarget.hasAVX512()) &&
32825              "Strict unsigned conversion requires AVX512");
32826       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32827       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32828              "Unexpected type action!");
32829       if (Src.getValueType() == MVT::v2f64) {
32830         if (!IsSigned && !Subtarget.hasAVX512()) {
32831           SDValue Res =
32832               expandFP_TO_UINT_SSE(MVT::v4i32, Src, dl, DAG, Subtarget);
32833           Results.push_back(Res);
32834           return;
32835         }
32836 
32837         unsigned Opc;
32838         if (IsStrict)
32839           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32840         else
32841           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32842 
32843         // If we have VLX we can emit a target specific FP_TO_UINT node,.
32844         if (!IsSigned && !Subtarget.hasVLX()) {
32845           // Otherwise we can defer to the generic legalizer which will widen
32846           // the input as well. This will be further widened during op
32847           // legalization to v8i32<-v8f64.
32848           // For strict nodes we'll need to widen ourselves.
32849           // FIXME: Fix the type legalizer to safely widen strict nodes?
32850           if (!IsStrict)
32851             return;
32852           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
32853                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
32854           Opc = N->getOpcode();
32855         }
32856         SDValue Res;
32857         SDValue Chain;
32858         if (IsStrict) {
32859           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
32860                             {N->getOperand(0), Src});
32861           Chain = Res.getValue(1);
32862         } else {
32863           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
32864         }
32865         Results.push_back(Res);
32866         if (IsStrict)
32867           Results.push_back(Chain);
32868         return;
32869       }
32870 
32871       // Custom widen strict v2f32->v2i32 by padding with zeros.
32872       // FIXME: Should generic type legalizer do this?
32873       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
32874         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
32875                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
32876         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
32877                                   {N->getOperand(0), Src});
32878         Results.push_back(Res);
32879         Results.push_back(Res.getValue(1));
32880         return;
32881       }
32882 
32883       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
32884       // so early out here.
32885       return;
32886     }
32887 
32888     assert(!VT.isVector() && "Vectors should have been handled above!");
32889 
32890     if ((Subtarget.hasDQI() && VT == MVT::i64 &&
32891          (SrcVT == MVT::f32 || SrcVT == MVT::f64)) ||
32892         (Subtarget.hasFP16() && SrcVT == MVT::f16)) {
32893       assert(!Subtarget.is64Bit() && "i64 should be legal");
32894       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
32895       // If we use a 128-bit result we might need to use a target specific node.
32896       unsigned SrcElts =
32897           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
32898       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
32899       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
32900       unsigned Opc = N->getOpcode();
32901       if (NumElts != SrcElts) {
32902         if (IsStrict)
32903           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32904         else
32905           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32906       }
32907 
32908       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
32909       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
32910                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
32911                                 ZeroIdx);
32912       SDValue Chain;
32913       if (IsStrict) {
32914         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
32915         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
32916         Chain = Res.getValue(1);
32917       } else
32918         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
32919       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
32920       Results.push_back(Res);
32921       if (IsStrict)
32922         Results.push_back(Chain);
32923       return;
32924     }
32925 
32926     if (VT == MVT::i128 && Subtarget.isTargetWin64()) {
32927       SDValue Chain;
32928       SDValue V = LowerWin64_FP_TO_INT128(SDValue(N, 0), DAG, Chain);
32929       Results.push_back(V);
32930       if (IsStrict)
32931         Results.push_back(Chain);
32932       return;
32933     }
32934 
32935     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
32936       Results.push_back(V);
32937       if (IsStrict)
32938         Results.push_back(Chain);
32939     }
32940     return;
32941   }
32942   case ISD::LRINT:
32943   case ISD::LLRINT: {
32944     if (SDValue V = LRINT_LLRINTHelper(N, DAG))
32945       Results.push_back(V);
32946     return;
32947   }
32948 
32949   case ISD::SINT_TO_FP:
32950   case ISD::STRICT_SINT_TO_FP:
32951   case ISD::UINT_TO_FP:
32952   case ISD::STRICT_UINT_TO_FP: {
32953     bool IsStrict = N->isStrictFPOpcode();
32954     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
32955                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
32956     EVT VT = N->getValueType(0);
32957     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32958     if (VT.getVectorElementType() == MVT::f16 && Subtarget.hasFP16() &&
32959         Subtarget.hasVLX()) {
32960       if (Src.getValueType().getVectorElementType() == MVT::i16)
32961         return;
32962 
32963       if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2i32)
32964         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
32965                           IsStrict ? DAG.getConstant(0, dl, MVT::v2i32)
32966                                    : DAG.getUNDEF(MVT::v2i32));
32967       if (IsStrict) {
32968         unsigned Opc =
32969             IsSigned ? X86ISD::STRICT_CVTSI2P : X86ISD::STRICT_CVTUI2P;
32970         SDValue Res = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
32971                                   {N->getOperand(0), Src});
32972         Results.push_back(Res);
32973         Results.push_back(Res.getValue(1));
32974       } else {
32975         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
32976         Results.push_back(DAG.getNode(Opc, dl, MVT::v8f16, Src));
32977       }
32978       return;
32979     }
32980     if (VT != MVT::v2f32)
32981       return;
32982     EVT SrcVT = Src.getValueType();
32983     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
32984       if (IsStrict) {
32985         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
32986                                 : X86ISD::STRICT_CVTUI2P;
32987         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
32988                                   {N->getOperand(0), Src});
32989         Results.push_back(Res);
32990         Results.push_back(Res.getValue(1));
32991       } else {
32992         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
32993         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
32994       }
32995       return;
32996     }
32997     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
32998         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
32999       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
33000       SDValue One  = DAG.getConstant(1, dl, SrcVT);
33001       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
33002                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
33003                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
33004       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
33005       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
33006       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
33007       for (int i = 0; i != 2; ++i) {
33008         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
33009                                   SignSrc, DAG.getIntPtrConstant(i, dl));
33010         if (IsStrict)
33011           SignCvts[i] =
33012               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
33013                           {N->getOperand(0), Elt});
33014         else
33015           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
33016       };
33017       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
33018       SDValue Slow, Chain;
33019       if (IsStrict) {
33020         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
33021                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
33022         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
33023                            {Chain, SignCvt, SignCvt});
33024         Chain = Slow.getValue(1);
33025       } else {
33026         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
33027       }
33028       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
33029       IsNeg =
33030           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
33031       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
33032       Results.push_back(Cvt);
33033       if (IsStrict)
33034         Results.push_back(Chain);
33035       return;
33036     }
33037 
33038     if (SrcVT != MVT::v2i32)
33039       return;
33040 
33041     if (IsSigned || Subtarget.hasAVX512()) {
33042       if (!IsStrict)
33043         return;
33044 
33045       // Custom widen strict v2i32->v2f32 to avoid scalarization.
33046       // FIXME: Should generic type legalizer do this?
33047       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
33048                         DAG.getConstant(0, dl, MVT::v2i32));
33049       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
33050                                 {N->getOperand(0), Src});
33051       Results.push_back(Res);
33052       Results.push_back(Res.getValue(1));
33053       return;
33054     }
33055 
33056     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
33057     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
33058     SDValue VBias =
33059         DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
33060     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
33061                              DAG.getBitcast(MVT::v2i64, VBias));
33062     Or = DAG.getBitcast(MVT::v2f64, Or);
33063     if (IsStrict) {
33064       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
33065                                 {N->getOperand(0), Or, VBias});
33066       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
33067                                 {MVT::v4f32, MVT::Other},
33068                                 {Sub.getValue(1), Sub});
33069       Results.push_back(Res);
33070       Results.push_back(Res.getValue(1));
33071     } else {
33072       // TODO: Are there any fast-math-flags to propagate here?
33073       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
33074       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
33075     }
33076     return;
33077   }
33078   case ISD::STRICT_FP_ROUND:
33079   case ISD::FP_ROUND: {
33080     bool IsStrict = N->isStrictFPOpcode();
33081     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
33082     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
33083     SDValue Rnd = N->getOperand(IsStrict ? 2 : 1);
33084     EVT SrcVT = Src.getValueType();
33085     EVT VT = N->getValueType(0);
33086     SDValue V;
33087     if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2f32) {
33088       SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f32)
33089                              : DAG.getUNDEF(MVT::v2f32);
33090       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src, Ext);
33091     }
33092     if (!Subtarget.hasFP16() && VT.getVectorElementType() == MVT::f16) {
33093       assert(Subtarget.hasF16C() && "Cannot widen f16 without F16C");
33094       if (SrcVT.getVectorElementType() != MVT::f32)
33095         return;
33096 
33097       if (IsStrict)
33098         V = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
33099                         {Chain, Src, Rnd});
33100       else
33101         V = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Src, Rnd);
33102 
33103       Results.push_back(DAG.getBitcast(MVT::v8f16, V));
33104       if (IsStrict)
33105         Results.push_back(V.getValue(1));
33106       return;
33107     }
33108     if (!isTypeLegal(Src.getValueType()))
33109       return;
33110     EVT NewVT = VT.getVectorElementType() == MVT::f16 ? MVT::v8f16 : MVT::v4f32;
33111     if (IsStrict)
33112       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {NewVT, MVT::Other},
33113                       {Chain, Src});
33114     else
33115       V = DAG.getNode(X86ISD::VFPROUND, dl, NewVT, Src);
33116     Results.push_back(V);
33117     if (IsStrict)
33118       Results.push_back(V.getValue(1));
33119     return;
33120   }
33121   case ISD::FP_EXTEND:
33122   case ISD::STRICT_FP_EXTEND: {
33123     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
33124     // No other ValueType for FP_EXTEND should reach this point.
33125     assert(N->getValueType(0) == MVT::v2f32 &&
33126            "Do not know how to legalize this Node");
33127     if (!Subtarget.hasFP16() || !Subtarget.hasVLX())
33128       return;
33129     bool IsStrict = N->isStrictFPOpcode();
33130     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
33131     SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f16)
33132                            : DAG.getUNDEF(MVT::v2f16);
33133     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f16, Src, Ext);
33134     if (IsStrict)
33135       V = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::v4f32, MVT::Other},
33136                       {N->getOperand(0), V});
33137     else
33138       V = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, V);
33139     Results.push_back(V);
33140     if (IsStrict)
33141       Results.push_back(V.getValue(1));
33142     return;
33143   }
33144   case ISD::INTRINSIC_W_CHAIN: {
33145     unsigned IntNo = N->getConstantOperandVal(1);
33146     switch (IntNo) {
33147     default : llvm_unreachable("Do not know how to custom type "
33148                                "legalize this intrinsic operation!");
33149     case Intrinsic::x86_rdtsc:
33150       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
33151                                      Results);
33152     case Intrinsic::x86_rdtscp:
33153       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
33154                                      Results);
33155     case Intrinsic::x86_rdpmc:
33156       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
33157                                   Results);
33158       return;
33159     case Intrinsic::x86_rdpru:
33160       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPRU, X86::ECX, Subtarget,
33161         Results);
33162       return;
33163     case Intrinsic::x86_xgetbv:
33164       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
33165                                   Results);
33166       return;
33167     }
33168   }
33169   case ISD::READCYCLECOUNTER: {
33170     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
33171   }
33172   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
33173     EVT T = N->getValueType(0);
33174     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
33175     bool Regs64bit = T == MVT::i128;
33176     assert((!Regs64bit || Subtarget.canUseCMPXCHG16B()) &&
33177            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
33178     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
33179     SDValue cpInL, cpInH;
33180     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
33181                         DAG.getConstant(0, dl, HalfT));
33182     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
33183                         DAG.getConstant(1, dl, HalfT));
33184     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
33185                              Regs64bit ? X86::RAX : X86::EAX,
33186                              cpInL, SDValue());
33187     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
33188                              Regs64bit ? X86::RDX : X86::EDX,
33189                              cpInH, cpInL.getValue(1));
33190     SDValue swapInL, swapInH;
33191     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
33192                           DAG.getConstant(0, dl, HalfT));
33193     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
33194                           DAG.getConstant(1, dl, HalfT));
33195     swapInH =
33196         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
33197                          swapInH, cpInH.getValue(1));
33198 
33199     // In 64-bit mode we might need the base pointer in RBX, but we can't know
33200     // until later. So we keep the RBX input in a vreg and use a custom
33201     // inserter.
33202     // Since RBX will be a reserved register the register allocator will not
33203     // make sure its value will be properly saved and restored around this
33204     // live-range.
33205     SDValue Result;
33206     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
33207     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
33208     if (Regs64bit) {
33209       SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
33210                        swapInH.getValue(1)};
33211       Result =
33212           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
33213     } else {
33214       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
33215                                  swapInH.getValue(1));
33216       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
33217                        swapInL.getValue(1)};
33218       Result =
33219           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
33220     }
33221 
33222     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
33223                                         Regs64bit ? X86::RAX : X86::EAX,
33224                                         HalfT, Result.getValue(1));
33225     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
33226                                         Regs64bit ? X86::RDX : X86::EDX,
33227                                         HalfT, cpOutL.getValue(2));
33228     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
33229 
33230     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
33231                                         MVT::i32, cpOutH.getValue(2));
33232     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
33233     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
33234 
33235     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
33236     Results.push_back(Success);
33237     Results.push_back(EFLAGS.getValue(1));
33238     return;
33239   }
33240   case ISD::ATOMIC_LOAD: {
33241     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
33242     bool NoImplicitFloatOps =
33243         DAG.getMachineFunction().getFunction().hasFnAttribute(
33244             Attribute::NoImplicitFloat);
33245     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
33246       auto *Node = cast<AtomicSDNode>(N);
33247       if (Subtarget.hasSSE1()) {
33248         // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
33249         // Then extract the lower 64-bits.
33250         MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
33251         SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
33252         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
33253         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
33254                                              MVT::i64, Node->getMemOperand());
33255         if (Subtarget.hasSSE2()) {
33256           SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
33257                                     DAG.getIntPtrConstant(0, dl));
33258           Results.push_back(Res);
33259           Results.push_back(Ld.getValue(1));
33260           return;
33261         }
33262         // We use an alternative sequence for SSE1 that extracts as v2f32 and
33263         // then casts to i64. This avoids a 128-bit stack temporary being
33264         // created by type legalization if we were to cast v4f32->v2i64.
33265         SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
33266                                   DAG.getIntPtrConstant(0, dl));
33267         Res = DAG.getBitcast(MVT::i64, Res);
33268         Results.push_back(Res);
33269         Results.push_back(Ld.getValue(1));
33270         return;
33271       }
33272       if (Subtarget.hasX87()) {
33273         // First load this into an 80-bit X87 register. This will put the whole
33274         // integer into the significand.
33275         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
33276         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
33277         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
33278                                                  dl, Tys, Ops, MVT::i64,
33279                                                  Node->getMemOperand());
33280         SDValue Chain = Result.getValue(1);
33281 
33282         // Now store the X87 register to a stack temporary and convert to i64.
33283         // This store is not atomic and doesn't need to be.
33284         // FIXME: We don't need a stack temporary if the result of the load
33285         // is already being stored. We could just directly store there.
33286         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
33287         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
33288         MachinePointerInfo MPI =
33289             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
33290         SDValue StoreOps[] = { Chain, Result, StackPtr };
33291         Chain = DAG.getMemIntrinsicNode(
33292             X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
33293             MPI, None /*Align*/, MachineMemOperand::MOStore);
33294 
33295         // Finally load the value back from the stack temporary and return it.
33296         // This load is not atomic and doesn't need to be.
33297         // This load will be further type legalized.
33298         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
33299         Results.push_back(Result);
33300         Results.push_back(Result.getValue(1));
33301         return;
33302       }
33303     }
33304     // TODO: Use MOVLPS when SSE1 is available?
33305     // Delegate to generic TypeLegalization. Situations we can really handle
33306     // should have already been dealt with by AtomicExpandPass.cpp.
33307     break;
33308   }
33309   case ISD::ATOMIC_SWAP:
33310   case ISD::ATOMIC_LOAD_ADD:
33311   case ISD::ATOMIC_LOAD_SUB:
33312   case ISD::ATOMIC_LOAD_AND:
33313   case ISD::ATOMIC_LOAD_OR:
33314   case ISD::ATOMIC_LOAD_XOR:
33315   case ISD::ATOMIC_LOAD_NAND:
33316   case ISD::ATOMIC_LOAD_MIN:
33317   case ISD::ATOMIC_LOAD_MAX:
33318   case ISD::ATOMIC_LOAD_UMIN:
33319   case ISD::ATOMIC_LOAD_UMAX:
33320     // Delegate to generic TypeLegalization. Situations we can really handle
33321     // should have already been dealt with by AtomicExpandPass.cpp.
33322     break;
33323 
33324   case ISD::BITCAST: {
33325     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
33326     EVT DstVT = N->getValueType(0);
33327     EVT SrcVT = N->getOperand(0).getValueType();
33328 
33329     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
33330     // we can split using the k-register rather than memory.
33331     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
33332       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
33333       SDValue Lo, Hi;
33334       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
33335       Lo = DAG.getBitcast(MVT::i32, Lo);
33336       Hi = DAG.getBitcast(MVT::i32, Hi);
33337       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
33338       Results.push_back(Res);
33339       return;
33340     }
33341 
33342     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
33343       // FIXME: Use v4f32 for SSE1?
33344       assert(Subtarget.hasSSE2() && "Requires SSE2");
33345       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
33346              "Unexpected type action!");
33347       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
33348       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
33349                                 N->getOperand(0));
33350       Res = DAG.getBitcast(WideVT, Res);
33351       Results.push_back(Res);
33352       return;
33353     }
33354 
33355     return;
33356   }
33357   case ISD::MGATHER: {
33358     EVT VT = N->getValueType(0);
33359     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
33360         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
33361       auto *Gather = cast<MaskedGatherSDNode>(N);
33362       SDValue Index = Gather->getIndex();
33363       if (Index.getValueType() != MVT::v2i64)
33364         return;
33365       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33366              "Unexpected type action!");
33367       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
33368       SDValue Mask = Gather->getMask();
33369       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
33370       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
33371                                      Gather->getPassThru(),
33372                                      DAG.getUNDEF(VT));
33373       if (!Subtarget.hasVLX()) {
33374         // We need to widen the mask, but the instruction will only use 2
33375         // of its elements. So we can use undef.
33376         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
33377                            DAG.getUNDEF(MVT::v2i1));
33378         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
33379       }
33380       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
33381                         Gather->getBasePtr(), Index, Gather->getScale() };
33382       SDValue Res = DAG.getMemIntrinsicNode(
33383           X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
33384           Gather->getMemoryVT(), Gather->getMemOperand());
33385       Results.push_back(Res);
33386       Results.push_back(Res.getValue(1));
33387       return;
33388     }
33389     return;
33390   }
33391   case ISD::LOAD: {
33392     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
33393     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
33394     // cast since type legalization will try to use an i64 load.
33395     MVT VT = N->getSimpleValueType(0);
33396     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
33397     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33398            "Unexpected type action!");
33399     if (!ISD::isNON_EXTLoad(N))
33400       return;
33401     auto *Ld = cast<LoadSDNode>(N);
33402     if (Subtarget.hasSSE2()) {
33403       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
33404       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
33405                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
33406                                 Ld->getMemOperand()->getFlags());
33407       SDValue Chain = Res.getValue(1);
33408       MVT VecVT = MVT::getVectorVT(LdVT, 2);
33409       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
33410       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
33411       Res = DAG.getBitcast(WideVT, Res);
33412       Results.push_back(Res);
33413       Results.push_back(Chain);
33414       return;
33415     }
33416     assert(Subtarget.hasSSE1() && "Expected SSE");
33417     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
33418     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
33419     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
33420                                           MVT::i64, Ld->getMemOperand());
33421     Results.push_back(Res);
33422     Results.push_back(Res.getValue(1));
33423     return;
33424   }
33425   case ISD::ADDRSPACECAST: {
33426     SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
33427     Results.push_back(V);
33428     return;
33429   }
33430   case ISD::BITREVERSE:
33431     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
33432     assert(Subtarget.hasXOP() && "Expected XOP");
33433     // We can use VPPERM by copying to a vector register and back. We'll need
33434     // to move the scalar in two i32 pieces.
33435     Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
33436     return;
33437   }
33438 }
33439 
33440 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
33441   switch ((X86ISD::NodeType)Opcode) {
33442   case X86ISD::FIRST_NUMBER:       break;
33443 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
33444   NODE_NAME_CASE(BSF)
33445   NODE_NAME_CASE(BSR)
33446   NODE_NAME_CASE(FSHL)
33447   NODE_NAME_CASE(FSHR)
33448   NODE_NAME_CASE(FAND)
33449   NODE_NAME_CASE(FANDN)
33450   NODE_NAME_CASE(FOR)
33451   NODE_NAME_CASE(FXOR)
33452   NODE_NAME_CASE(FILD)
33453   NODE_NAME_CASE(FIST)
33454   NODE_NAME_CASE(FP_TO_INT_IN_MEM)
33455   NODE_NAME_CASE(FLD)
33456   NODE_NAME_CASE(FST)
33457   NODE_NAME_CASE(CALL)
33458   NODE_NAME_CASE(CALL_RVMARKER)
33459   NODE_NAME_CASE(BT)
33460   NODE_NAME_CASE(CMP)
33461   NODE_NAME_CASE(FCMP)
33462   NODE_NAME_CASE(STRICT_FCMP)
33463   NODE_NAME_CASE(STRICT_FCMPS)
33464   NODE_NAME_CASE(COMI)
33465   NODE_NAME_CASE(UCOMI)
33466   NODE_NAME_CASE(CMPM)
33467   NODE_NAME_CASE(CMPMM)
33468   NODE_NAME_CASE(STRICT_CMPM)
33469   NODE_NAME_CASE(CMPMM_SAE)
33470   NODE_NAME_CASE(SETCC)
33471   NODE_NAME_CASE(SETCC_CARRY)
33472   NODE_NAME_CASE(FSETCC)
33473   NODE_NAME_CASE(FSETCCM)
33474   NODE_NAME_CASE(FSETCCM_SAE)
33475   NODE_NAME_CASE(CMOV)
33476   NODE_NAME_CASE(BRCOND)
33477   NODE_NAME_CASE(RET_FLAG)
33478   NODE_NAME_CASE(IRET)
33479   NODE_NAME_CASE(REP_STOS)
33480   NODE_NAME_CASE(REP_MOVS)
33481   NODE_NAME_CASE(GlobalBaseReg)
33482   NODE_NAME_CASE(Wrapper)
33483   NODE_NAME_CASE(WrapperRIP)
33484   NODE_NAME_CASE(MOVQ2DQ)
33485   NODE_NAME_CASE(MOVDQ2Q)
33486   NODE_NAME_CASE(MMX_MOVD2W)
33487   NODE_NAME_CASE(MMX_MOVW2D)
33488   NODE_NAME_CASE(PEXTRB)
33489   NODE_NAME_CASE(PEXTRW)
33490   NODE_NAME_CASE(INSERTPS)
33491   NODE_NAME_CASE(PINSRB)
33492   NODE_NAME_CASE(PINSRW)
33493   NODE_NAME_CASE(PSHUFB)
33494   NODE_NAME_CASE(ANDNP)
33495   NODE_NAME_CASE(BLENDI)
33496   NODE_NAME_CASE(BLENDV)
33497   NODE_NAME_CASE(HADD)
33498   NODE_NAME_CASE(HSUB)
33499   NODE_NAME_CASE(FHADD)
33500   NODE_NAME_CASE(FHSUB)
33501   NODE_NAME_CASE(CONFLICT)
33502   NODE_NAME_CASE(FMAX)
33503   NODE_NAME_CASE(FMAXS)
33504   NODE_NAME_CASE(FMAX_SAE)
33505   NODE_NAME_CASE(FMAXS_SAE)
33506   NODE_NAME_CASE(FMIN)
33507   NODE_NAME_CASE(FMINS)
33508   NODE_NAME_CASE(FMIN_SAE)
33509   NODE_NAME_CASE(FMINS_SAE)
33510   NODE_NAME_CASE(FMAXC)
33511   NODE_NAME_CASE(FMINC)
33512   NODE_NAME_CASE(FRSQRT)
33513   NODE_NAME_CASE(FRCP)
33514   NODE_NAME_CASE(EXTRQI)
33515   NODE_NAME_CASE(INSERTQI)
33516   NODE_NAME_CASE(TLSADDR)
33517   NODE_NAME_CASE(TLSBASEADDR)
33518   NODE_NAME_CASE(TLSCALL)
33519   NODE_NAME_CASE(EH_SJLJ_SETJMP)
33520   NODE_NAME_CASE(EH_SJLJ_LONGJMP)
33521   NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
33522   NODE_NAME_CASE(EH_RETURN)
33523   NODE_NAME_CASE(TC_RETURN)
33524   NODE_NAME_CASE(FNSTCW16m)
33525   NODE_NAME_CASE(FLDCW16m)
33526   NODE_NAME_CASE(LCMPXCHG_DAG)
33527   NODE_NAME_CASE(LCMPXCHG8_DAG)
33528   NODE_NAME_CASE(LCMPXCHG16_DAG)
33529   NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
33530   NODE_NAME_CASE(LADD)
33531   NODE_NAME_CASE(LSUB)
33532   NODE_NAME_CASE(LOR)
33533   NODE_NAME_CASE(LXOR)
33534   NODE_NAME_CASE(LAND)
33535   NODE_NAME_CASE(LBTS)
33536   NODE_NAME_CASE(LBTC)
33537   NODE_NAME_CASE(LBTR)
33538   NODE_NAME_CASE(VZEXT_MOVL)
33539   NODE_NAME_CASE(VZEXT_LOAD)
33540   NODE_NAME_CASE(VEXTRACT_STORE)
33541   NODE_NAME_CASE(VTRUNC)
33542   NODE_NAME_CASE(VTRUNCS)
33543   NODE_NAME_CASE(VTRUNCUS)
33544   NODE_NAME_CASE(VMTRUNC)
33545   NODE_NAME_CASE(VMTRUNCS)
33546   NODE_NAME_CASE(VMTRUNCUS)
33547   NODE_NAME_CASE(VTRUNCSTORES)
33548   NODE_NAME_CASE(VTRUNCSTOREUS)
33549   NODE_NAME_CASE(VMTRUNCSTORES)
33550   NODE_NAME_CASE(VMTRUNCSTOREUS)
33551   NODE_NAME_CASE(VFPEXT)
33552   NODE_NAME_CASE(STRICT_VFPEXT)
33553   NODE_NAME_CASE(VFPEXT_SAE)
33554   NODE_NAME_CASE(VFPEXTS)
33555   NODE_NAME_CASE(VFPEXTS_SAE)
33556   NODE_NAME_CASE(VFPROUND)
33557   NODE_NAME_CASE(STRICT_VFPROUND)
33558   NODE_NAME_CASE(VMFPROUND)
33559   NODE_NAME_CASE(VFPROUND_RND)
33560   NODE_NAME_CASE(VFPROUNDS)
33561   NODE_NAME_CASE(VFPROUNDS_RND)
33562   NODE_NAME_CASE(VSHLDQ)
33563   NODE_NAME_CASE(VSRLDQ)
33564   NODE_NAME_CASE(VSHL)
33565   NODE_NAME_CASE(VSRL)
33566   NODE_NAME_CASE(VSRA)
33567   NODE_NAME_CASE(VSHLI)
33568   NODE_NAME_CASE(VSRLI)
33569   NODE_NAME_CASE(VSRAI)
33570   NODE_NAME_CASE(VSHLV)
33571   NODE_NAME_CASE(VSRLV)
33572   NODE_NAME_CASE(VSRAV)
33573   NODE_NAME_CASE(VROTLI)
33574   NODE_NAME_CASE(VROTRI)
33575   NODE_NAME_CASE(VPPERM)
33576   NODE_NAME_CASE(CMPP)
33577   NODE_NAME_CASE(STRICT_CMPP)
33578   NODE_NAME_CASE(PCMPEQ)
33579   NODE_NAME_CASE(PCMPGT)
33580   NODE_NAME_CASE(PHMINPOS)
33581   NODE_NAME_CASE(ADD)
33582   NODE_NAME_CASE(SUB)
33583   NODE_NAME_CASE(ADC)
33584   NODE_NAME_CASE(SBB)
33585   NODE_NAME_CASE(SMUL)
33586   NODE_NAME_CASE(UMUL)
33587   NODE_NAME_CASE(OR)
33588   NODE_NAME_CASE(XOR)
33589   NODE_NAME_CASE(AND)
33590   NODE_NAME_CASE(BEXTR)
33591   NODE_NAME_CASE(BEXTRI)
33592   NODE_NAME_CASE(BZHI)
33593   NODE_NAME_CASE(PDEP)
33594   NODE_NAME_CASE(PEXT)
33595   NODE_NAME_CASE(MUL_IMM)
33596   NODE_NAME_CASE(MOVMSK)
33597   NODE_NAME_CASE(PTEST)
33598   NODE_NAME_CASE(TESTP)
33599   NODE_NAME_CASE(KORTEST)
33600   NODE_NAME_CASE(KTEST)
33601   NODE_NAME_CASE(KADD)
33602   NODE_NAME_CASE(KSHIFTL)
33603   NODE_NAME_CASE(KSHIFTR)
33604   NODE_NAME_CASE(PACKSS)
33605   NODE_NAME_CASE(PACKUS)
33606   NODE_NAME_CASE(PALIGNR)
33607   NODE_NAME_CASE(VALIGN)
33608   NODE_NAME_CASE(VSHLD)
33609   NODE_NAME_CASE(VSHRD)
33610   NODE_NAME_CASE(VSHLDV)
33611   NODE_NAME_CASE(VSHRDV)
33612   NODE_NAME_CASE(PSHUFD)
33613   NODE_NAME_CASE(PSHUFHW)
33614   NODE_NAME_CASE(PSHUFLW)
33615   NODE_NAME_CASE(SHUFP)
33616   NODE_NAME_CASE(SHUF128)
33617   NODE_NAME_CASE(MOVLHPS)
33618   NODE_NAME_CASE(MOVHLPS)
33619   NODE_NAME_CASE(MOVDDUP)
33620   NODE_NAME_CASE(MOVSHDUP)
33621   NODE_NAME_CASE(MOVSLDUP)
33622   NODE_NAME_CASE(MOVSD)
33623   NODE_NAME_CASE(MOVSS)
33624   NODE_NAME_CASE(MOVSH)
33625   NODE_NAME_CASE(UNPCKL)
33626   NODE_NAME_CASE(UNPCKH)
33627   NODE_NAME_CASE(VBROADCAST)
33628   NODE_NAME_CASE(VBROADCAST_LOAD)
33629   NODE_NAME_CASE(VBROADCASTM)
33630   NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
33631   NODE_NAME_CASE(VPERMILPV)
33632   NODE_NAME_CASE(VPERMILPI)
33633   NODE_NAME_CASE(VPERM2X128)
33634   NODE_NAME_CASE(VPERMV)
33635   NODE_NAME_CASE(VPERMV3)
33636   NODE_NAME_CASE(VPERMI)
33637   NODE_NAME_CASE(VPTERNLOG)
33638   NODE_NAME_CASE(VFIXUPIMM)
33639   NODE_NAME_CASE(VFIXUPIMM_SAE)
33640   NODE_NAME_CASE(VFIXUPIMMS)
33641   NODE_NAME_CASE(VFIXUPIMMS_SAE)
33642   NODE_NAME_CASE(VRANGE)
33643   NODE_NAME_CASE(VRANGE_SAE)
33644   NODE_NAME_CASE(VRANGES)
33645   NODE_NAME_CASE(VRANGES_SAE)
33646   NODE_NAME_CASE(PMULUDQ)
33647   NODE_NAME_CASE(PMULDQ)
33648   NODE_NAME_CASE(PSADBW)
33649   NODE_NAME_CASE(DBPSADBW)
33650   NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
33651   NODE_NAME_CASE(VAARG_64)
33652   NODE_NAME_CASE(VAARG_X32)
33653   NODE_NAME_CASE(DYN_ALLOCA)
33654   NODE_NAME_CASE(MEMBARRIER)
33655   NODE_NAME_CASE(MFENCE)
33656   NODE_NAME_CASE(SEG_ALLOCA)
33657   NODE_NAME_CASE(PROBED_ALLOCA)
33658   NODE_NAME_CASE(RDRAND)
33659   NODE_NAME_CASE(RDSEED)
33660   NODE_NAME_CASE(RDPKRU)
33661   NODE_NAME_CASE(WRPKRU)
33662   NODE_NAME_CASE(VPMADDUBSW)
33663   NODE_NAME_CASE(VPMADDWD)
33664   NODE_NAME_CASE(VPSHA)
33665   NODE_NAME_CASE(VPSHL)
33666   NODE_NAME_CASE(VPCOM)
33667   NODE_NAME_CASE(VPCOMU)
33668   NODE_NAME_CASE(VPERMIL2)
33669   NODE_NAME_CASE(FMSUB)
33670   NODE_NAME_CASE(STRICT_FMSUB)
33671   NODE_NAME_CASE(FNMADD)
33672   NODE_NAME_CASE(STRICT_FNMADD)
33673   NODE_NAME_CASE(FNMSUB)
33674   NODE_NAME_CASE(STRICT_FNMSUB)
33675   NODE_NAME_CASE(FMADDSUB)
33676   NODE_NAME_CASE(FMSUBADD)
33677   NODE_NAME_CASE(FMADD_RND)
33678   NODE_NAME_CASE(FNMADD_RND)
33679   NODE_NAME_CASE(FMSUB_RND)
33680   NODE_NAME_CASE(FNMSUB_RND)
33681   NODE_NAME_CASE(FMADDSUB_RND)
33682   NODE_NAME_CASE(FMSUBADD_RND)
33683   NODE_NAME_CASE(VFMADDC)
33684   NODE_NAME_CASE(VFMADDC_RND)
33685   NODE_NAME_CASE(VFCMADDC)
33686   NODE_NAME_CASE(VFCMADDC_RND)
33687   NODE_NAME_CASE(VFMULC)
33688   NODE_NAME_CASE(VFMULC_RND)
33689   NODE_NAME_CASE(VFCMULC)
33690   NODE_NAME_CASE(VFCMULC_RND)
33691   NODE_NAME_CASE(VFMULCSH)
33692   NODE_NAME_CASE(VFMULCSH_RND)
33693   NODE_NAME_CASE(VFCMULCSH)
33694   NODE_NAME_CASE(VFCMULCSH_RND)
33695   NODE_NAME_CASE(VFMADDCSH)
33696   NODE_NAME_CASE(VFMADDCSH_RND)
33697   NODE_NAME_CASE(VFCMADDCSH)
33698   NODE_NAME_CASE(VFCMADDCSH_RND)
33699   NODE_NAME_CASE(VPMADD52H)
33700   NODE_NAME_CASE(VPMADD52L)
33701   NODE_NAME_CASE(VRNDSCALE)
33702   NODE_NAME_CASE(STRICT_VRNDSCALE)
33703   NODE_NAME_CASE(VRNDSCALE_SAE)
33704   NODE_NAME_CASE(VRNDSCALES)
33705   NODE_NAME_CASE(VRNDSCALES_SAE)
33706   NODE_NAME_CASE(VREDUCE)
33707   NODE_NAME_CASE(VREDUCE_SAE)
33708   NODE_NAME_CASE(VREDUCES)
33709   NODE_NAME_CASE(VREDUCES_SAE)
33710   NODE_NAME_CASE(VGETMANT)
33711   NODE_NAME_CASE(VGETMANT_SAE)
33712   NODE_NAME_CASE(VGETMANTS)
33713   NODE_NAME_CASE(VGETMANTS_SAE)
33714   NODE_NAME_CASE(PCMPESTR)
33715   NODE_NAME_CASE(PCMPISTR)
33716   NODE_NAME_CASE(XTEST)
33717   NODE_NAME_CASE(COMPRESS)
33718   NODE_NAME_CASE(EXPAND)
33719   NODE_NAME_CASE(SELECTS)
33720   NODE_NAME_CASE(ADDSUB)
33721   NODE_NAME_CASE(RCP14)
33722   NODE_NAME_CASE(RCP14S)
33723   NODE_NAME_CASE(RCP28)
33724   NODE_NAME_CASE(RCP28_SAE)
33725   NODE_NAME_CASE(RCP28S)
33726   NODE_NAME_CASE(RCP28S_SAE)
33727   NODE_NAME_CASE(EXP2)
33728   NODE_NAME_CASE(EXP2_SAE)
33729   NODE_NAME_CASE(RSQRT14)
33730   NODE_NAME_CASE(RSQRT14S)
33731   NODE_NAME_CASE(RSQRT28)
33732   NODE_NAME_CASE(RSQRT28_SAE)
33733   NODE_NAME_CASE(RSQRT28S)
33734   NODE_NAME_CASE(RSQRT28S_SAE)
33735   NODE_NAME_CASE(FADD_RND)
33736   NODE_NAME_CASE(FADDS)
33737   NODE_NAME_CASE(FADDS_RND)
33738   NODE_NAME_CASE(FSUB_RND)
33739   NODE_NAME_CASE(FSUBS)
33740   NODE_NAME_CASE(FSUBS_RND)
33741   NODE_NAME_CASE(FMUL_RND)
33742   NODE_NAME_CASE(FMULS)
33743   NODE_NAME_CASE(FMULS_RND)
33744   NODE_NAME_CASE(FDIV_RND)
33745   NODE_NAME_CASE(FDIVS)
33746   NODE_NAME_CASE(FDIVS_RND)
33747   NODE_NAME_CASE(FSQRT_RND)
33748   NODE_NAME_CASE(FSQRTS)
33749   NODE_NAME_CASE(FSQRTS_RND)
33750   NODE_NAME_CASE(FGETEXP)
33751   NODE_NAME_CASE(FGETEXP_SAE)
33752   NODE_NAME_CASE(FGETEXPS)
33753   NODE_NAME_CASE(FGETEXPS_SAE)
33754   NODE_NAME_CASE(SCALEF)
33755   NODE_NAME_CASE(SCALEF_RND)
33756   NODE_NAME_CASE(SCALEFS)
33757   NODE_NAME_CASE(SCALEFS_RND)
33758   NODE_NAME_CASE(MULHRS)
33759   NODE_NAME_CASE(SINT_TO_FP_RND)
33760   NODE_NAME_CASE(UINT_TO_FP_RND)
33761   NODE_NAME_CASE(CVTTP2SI)
33762   NODE_NAME_CASE(CVTTP2UI)
33763   NODE_NAME_CASE(STRICT_CVTTP2SI)
33764   NODE_NAME_CASE(STRICT_CVTTP2UI)
33765   NODE_NAME_CASE(MCVTTP2SI)
33766   NODE_NAME_CASE(MCVTTP2UI)
33767   NODE_NAME_CASE(CVTTP2SI_SAE)
33768   NODE_NAME_CASE(CVTTP2UI_SAE)
33769   NODE_NAME_CASE(CVTTS2SI)
33770   NODE_NAME_CASE(CVTTS2UI)
33771   NODE_NAME_CASE(CVTTS2SI_SAE)
33772   NODE_NAME_CASE(CVTTS2UI_SAE)
33773   NODE_NAME_CASE(CVTSI2P)
33774   NODE_NAME_CASE(CVTUI2P)
33775   NODE_NAME_CASE(STRICT_CVTSI2P)
33776   NODE_NAME_CASE(STRICT_CVTUI2P)
33777   NODE_NAME_CASE(MCVTSI2P)
33778   NODE_NAME_CASE(MCVTUI2P)
33779   NODE_NAME_CASE(VFPCLASS)
33780   NODE_NAME_CASE(VFPCLASSS)
33781   NODE_NAME_CASE(MULTISHIFT)
33782   NODE_NAME_CASE(SCALAR_SINT_TO_FP)
33783   NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
33784   NODE_NAME_CASE(SCALAR_UINT_TO_FP)
33785   NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
33786   NODE_NAME_CASE(CVTPS2PH)
33787   NODE_NAME_CASE(STRICT_CVTPS2PH)
33788   NODE_NAME_CASE(MCVTPS2PH)
33789   NODE_NAME_CASE(CVTPH2PS)
33790   NODE_NAME_CASE(STRICT_CVTPH2PS)
33791   NODE_NAME_CASE(CVTPH2PS_SAE)
33792   NODE_NAME_CASE(CVTP2SI)
33793   NODE_NAME_CASE(CVTP2UI)
33794   NODE_NAME_CASE(MCVTP2SI)
33795   NODE_NAME_CASE(MCVTP2UI)
33796   NODE_NAME_CASE(CVTP2SI_RND)
33797   NODE_NAME_CASE(CVTP2UI_RND)
33798   NODE_NAME_CASE(CVTS2SI)
33799   NODE_NAME_CASE(CVTS2UI)
33800   NODE_NAME_CASE(CVTS2SI_RND)
33801   NODE_NAME_CASE(CVTS2UI_RND)
33802   NODE_NAME_CASE(CVTNE2PS2BF16)
33803   NODE_NAME_CASE(CVTNEPS2BF16)
33804   NODE_NAME_CASE(MCVTNEPS2BF16)
33805   NODE_NAME_CASE(DPBF16PS)
33806   NODE_NAME_CASE(LWPINS)
33807   NODE_NAME_CASE(MGATHER)
33808   NODE_NAME_CASE(MSCATTER)
33809   NODE_NAME_CASE(VPDPBUSD)
33810   NODE_NAME_CASE(VPDPBUSDS)
33811   NODE_NAME_CASE(VPDPWSSD)
33812   NODE_NAME_CASE(VPDPWSSDS)
33813   NODE_NAME_CASE(VPSHUFBITQMB)
33814   NODE_NAME_CASE(GF2P8MULB)
33815   NODE_NAME_CASE(GF2P8AFFINEQB)
33816   NODE_NAME_CASE(GF2P8AFFINEINVQB)
33817   NODE_NAME_CASE(NT_CALL)
33818   NODE_NAME_CASE(NT_BRIND)
33819   NODE_NAME_CASE(UMWAIT)
33820   NODE_NAME_CASE(TPAUSE)
33821   NODE_NAME_CASE(ENQCMD)
33822   NODE_NAME_CASE(ENQCMDS)
33823   NODE_NAME_CASE(VP2INTERSECT)
33824   NODE_NAME_CASE(AESENC128KL)
33825   NODE_NAME_CASE(AESDEC128KL)
33826   NODE_NAME_CASE(AESENC256KL)
33827   NODE_NAME_CASE(AESDEC256KL)
33828   NODE_NAME_CASE(AESENCWIDE128KL)
33829   NODE_NAME_CASE(AESDECWIDE128KL)
33830   NODE_NAME_CASE(AESENCWIDE256KL)
33831   NODE_NAME_CASE(AESDECWIDE256KL)
33832   NODE_NAME_CASE(TESTUI)
33833   }
33834   return nullptr;
33835 #undef NODE_NAME_CASE
33836 }
33837 
33838 /// Return true if the addressing mode represented by AM is legal for this
33839 /// target, for a load/store of the specified type.
33840 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
33841                                               const AddrMode &AM, Type *Ty,
33842                                               unsigned AS,
33843                                               Instruction *I) const {
33844   // X86 supports extremely general addressing modes.
33845   CodeModel::Model M = getTargetMachine().getCodeModel();
33846 
33847   // X86 allows a sign-extended 32-bit immediate field as a displacement.
33848   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
33849     return false;
33850 
33851   if (AM.BaseGV) {
33852     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
33853 
33854     // If a reference to this global requires an extra load, we can't fold it.
33855     if (isGlobalStubReference(GVFlags))
33856       return false;
33857 
33858     // If BaseGV requires a register for the PIC base, we cannot also have a
33859     // BaseReg specified.
33860     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
33861       return false;
33862 
33863     // If lower 4G is not available, then we must use rip-relative addressing.
33864     if ((M != CodeModel::Small || isPositionIndependent()) &&
33865         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
33866       return false;
33867   }
33868 
33869   switch (AM.Scale) {
33870   case 0:
33871   case 1:
33872   case 2:
33873   case 4:
33874   case 8:
33875     // These scales always work.
33876     break;
33877   case 3:
33878   case 5:
33879   case 9:
33880     // These scales are formed with basereg+scalereg.  Only accept if there is
33881     // no basereg yet.
33882     if (AM.HasBaseReg)
33883       return false;
33884     break;
33885   default:  // Other stuff never works.
33886     return false;
33887   }
33888 
33889   return true;
33890 }
33891 
33892 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
33893   unsigned Bits = Ty->getScalarSizeInBits();
33894 
33895   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
33896   // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
33897   if (Subtarget.hasXOP() &&
33898       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
33899     return false;
33900 
33901   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
33902   // shifts just as cheap as scalar ones.
33903   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
33904     return false;
33905 
33906   // AVX512BW has shifts such as vpsllvw.
33907   if (Subtarget.hasBWI() && Bits == 16)
33908     return false;
33909 
33910   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
33911   // fully general vector.
33912   return true;
33913 }
33914 
33915 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
33916   switch (Opcode) {
33917   // These are non-commutative binops.
33918   // TODO: Add more X86ISD opcodes once we have test coverage.
33919   case X86ISD::ANDNP:
33920   case X86ISD::PCMPGT:
33921   case X86ISD::FMAX:
33922   case X86ISD::FMIN:
33923   case X86ISD::FANDN:
33924   case X86ISD::VPSHA:
33925   case X86ISD::VPSHL:
33926   case X86ISD::VSHLV:
33927   case X86ISD::VSRLV:
33928   case X86ISD::VSRAV:
33929     return true;
33930   }
33931 
33932   return TargetLoweringBase::isBinOp(Opcode);
33933 }
33934 
33935 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
33936   switch (Opcode) {
33937   // TODO: Add more X86ISD opcodes once we have test coverage.
33938   case X86ISD::PCMPEQ:
33939   case X86ISD::PMULDQ:
33940   case X86ISD::PMULUDQ:
33941   case X86ISD::FMAXC:
33942   case X86ISD::FMINC:
33943   case X86ISD::FAND:
33944   case X86ISD::FOR:
33945   case X86ISD::FXOR:
33946     return true;
33947   }
33948 
33949   return TargetLoweringBase::isCommutativeBinOp(Opcode);
33950 }
33951 
33952 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
33953   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
33954     return false;
33955   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
33956   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
33957   return NumBits1 > NumBits2;
33958 }
33959 
33960 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
33961   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
33962     return false;
33963 
33964   if (!isTypeLegal(EVT::getEVT(Ty1)))
33965     return false;
33966 
33967   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
33968 
33969   // Assuming the caller doesn't have a zeroext or signext return parameter,
33970   // truncation all the way down to i1 is valid.
33971   return true;
33972 }
33973 
33974 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
33975   return isInt<32>(Imm);
33976 }
33977 
33978 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
33979   // Can also use sub to handle negated immediates.
33980   return isInt<32>(Imm);
33981 }
33982 
33983 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
33984   return isInt<32>(Imm);
33985 }
33986 
33987 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
33988   if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
33989     return false;
33990   unsigned NumBits1 = VT1.getSizeInBits();
33991   unsigned NumBits2 = VT2.getSizeInBits();
33992   return NumBits1 > NumBits2;
33993 }
33994 
33995 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
33996   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
33997   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
33998 }
33999 
34000 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
34001   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
34002   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
34003 }
34004 
34005 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
34006   EVT VT1 = Val.getValueType();
34007   if (isZExtFree(VT1, VT2))
34008     return true;
34009 
34010   if (Val.getOpcode() != ISD::LOAD)
34011     return false;
34012 
34013   if (!VT1.isSimple() || !VT1.isInteger() ||
34014       !VT2.isSimple() || !VT2.isInteger())
34015     return false;
34016 
34017   switch (VT1.getSimpleVT().SimpleTy) {
34018   default: break;
34019   case MVT::i8:
34020   case MVT::i16:
34021   case MVT::i32:
34022     // X86 has 8, 16, and 32-bit zero-extending loads.
34023     return true;
34024   }
34025 
34026   return false;
34027 }
34028 
34029 bool X86TargetLowering::shouldSinkOperands(Instruction *I,
34030                                            SmallVectorImpl<Use *> &Ops) const {
34031   using namespace llvm::PatternMatch;
34032 
34033   FixedVectorType *VTy = dyn_cast<FixedVectorType>(I->getType());
34034   if (!VTy)
34035     return false;
34036 
34037   if (I->getOpcode() == Instruction::Mul &&
34038       VTy->getElementType()->isIntegerTy(64)) {
34039     for (auto &Op : I->operands()) {
34040       // Make sure we are not already sinking this operand
34041       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
34042         continue;
34043 
34044       // Look for PMULDQ pattern where the input is a sext_inreg from vXi32 or
34045       // the PMULUDQ pattern where the input is a zext_inreg from vXi32.
34046       if (Subtarget.hasSSE41() &&
34047           match(Op.get(), m_AShr(m_Shl(m_Value(), m_SpecificInt(32)),
34048                                  m_SpecificInt(32)))) {
34049         Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
34050         Ops.push_back(&Op);
34051       } else if (Subtarget.hasSSE2() &&
34052                  match(Op.get(),
34053                        m_And(m_Value(), m_SpecificInt(UINT64_C(0xffffffff))))) {
34054         Ops.push_back(&Op);
34055       }
34056     }
34057 
34058     return !Ops.empty();
34059   }
34060 
34061   // A uniform shift amount in a vector shift or funnel shift may be much
34062   // cheaper than a generic variable vector shift, so make that pattern visible
34063   // to SDAG by sinking the shuffle instruction next to the shift.
34064   int ShiftAmountOpNum = -1;
34065   if (I->isShift())
34066     ShiftAmountOpNum = 1;
34067   else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
34068     if (II->getIntrinsicID() == Intrinsic::fshl ||
34069         II->getIntrinsicID() == Intrinsic::fshr)
34070       ShiftAmountOpNum = 2;
34071   }
34072 
34073   if (ShiftAmountOpNum == -1)
34074     return false;
34075 
34076   auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
34077   if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
34078       isVectorShiftByScalarCheap(I->getType())) {
34079     Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
34080     return true;
34081   }
34082 
34083   return false;
34084 }
34085 
34086 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
34087   if (!Subtarget.is64Bit())
34088     return false;
34089   return TargetLowering::shouldConvertPhiType(From, To);
34090 }
34091 
34092 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
34093   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
34094     return false;
34095 
34096   EVT SrcVT = ExtVal.getOperand(0).getValueType();
34097 
34098   // There is no extending load for vXi1.
34099   if (SrcVT.getScalarType() == MVT::i1)
34100     return false;
34101 
34102   return true;
34103 }
34104 
34105 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
34106                                                    EVT VT) const {
34107   if (!Subtarget.hasAnyFMA())
34108     return false;
34109 
34110   VT = VT.getScalarType();
34111 
34112   if (!VT.isSimple())
34113     return false;
34114 
34115   switch (VT.getSimpleVT().SimpleTy) {
34116   case MVT::f16:
34117     return Subtarget.hasFP16();
34118   case MVT::f32:
34119   case MVT::f64:
34120     return true;
34121   default:
34122     break;
34123   }
34124 
34125   return false;
34126 }
34127 
34128 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
34129   // i16 instructions are longer (0x66 prefix) and potentially slower.
34130   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
34131 }
34132 
34133 bool X86TargetLowering::shouldFoldSelectWithIdentityConstant(unsigned Opcode,
34134                                                              EVT VT) const {
34135   // TODO: This is too general. There are cases where pre-AVX512 codegen would
34136   //       benefit. The transform may also be profitable for scalar code.
34137   if (!Subtarget.hasAVX512())
34138     return false;
34139   if (!Subtarget.hasVLX() && !VT.is512BitVector())
34140     return false;
34141   if (!VT.isVector())
34142     return false;
34143 
34144   return true;
34145 }
34146 
34147 /// Targets can use this to indicate that they only support *some*
34148 /// VECTOR_SHUFFLE operations, those with specific masks.
34149 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
34150 /// are assumed to be legal.
34151 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
34152   if (!VT.isSimple())
34153     return false;
34154 
34155   // Not for i1 vectors
34156   if (VT.getSimpleVT().getScalarType() == MVT::i1)
34157     return false;
34158 
34159   // Very little shuffling can be done for 64-bit vectors right now.
34160   if (VT.getSimpleVT().getSizeInBits() == 64)
34161     return false;
34162 
34163   // We only care that the types being shuffled are legal. The lowering can
34164   // handle any possible shuffle mask that results.
34165   return isTypeLegal(VT.getSimpleVT());
34166 }
34167 
34168 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
34169                                                EVT VT) const {
34170   // Don't convert an 'and' into a shuffle that we don't directly support.
34171   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
34172   if (!Subtarget.hasAVX2())
34173     if (VT == MVT::v32i8 || VT == MVT::v16i16)
34174       return false;
34175 
34176   // Just delegate to the generic legality, clear masks aren't special.
34177   return isShuffleMaskLegal(Mask, VT);
34178 }
34179 
34180 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
34181   // If the subtarget is using thunks, we need to not generate jump tables.
34182   if (Subtarget.useIndirectThunkBranches())
34183     return false;
34184 
34185   // Otherwise, fallback on the generic logic.
34186   return TargetLowering::areJTsAllowed(Fn);
34187 }
34188 
34189 MVT X86TargetLowering::getPreferredSwitchConditionType(LLVMContext &Context,
34190                                                        EVT ConditionVT) const {
34191   // Avoid 8 and 16 bit types because they increase the chance for unnecessary
34192   // zero-extensions.
34193   if (ConditionVT.getSizeInBits() < 32)
34194     return MVT::i32;
34195   return TargetLoweringBase::getPreferredSwitchConditionType(Context,
34196                                                              ConditionVT);
34197 }
34198 
34199 //===----------------------------------------------------------------------===//
34200 //                           X86 Scheduler Hooks
34201 //===----------------------------------------------------------------------===//
34202 
34203 // Returns true if EFLAG is consumed after this iterator in the rest of the
34204 // basic block or any successors of the basic block.
34205 static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
34206                               MachineBasicBlock *BB) {
34207   // Scan forward through BB for a use/def of EFLAGS.
34208   for (const MachineInstr &mi : llvm::make_range(std::next(Itr), BB->end())) {
34209     if (mi.readsRegister(X86::EFLAGS))
34210       return true;
34211     // If we found a def, we can stop searching.
34212     if (mi.definesRegister(X86::EFLAGS))
34213       return false;
34214   }
34215 
34216   // If we hit the end of the block, check whether EFLAGS is live into a
34217   // successor.
34218   for (MachineBasicBlock *Succ : BB->successors())
34219     if (Succ->isLiveIn(X86::EFLAGS))
34220       return true;
34221 
34222   return false;
34223 }
34224 
34225 /// Utility function to emit xbegin specifying the start of an RTM region.
34226 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
34227                                      const TargetInstrInfo *TII) {
34228   const DebugLoc &DL = MI.getDebugLoc();
34229 
34230   const BasicBlock *BB = MBB->getBasicBlock();
34231   MachineFunction::iterator I = ++MBB->getIterator();
34232 
34233   // For the v = xbegin(), we generate
34234   //
34235   // thisMBB:
34236   //  xbegin sinkMBB
34237   //
34238   // mainMBB:
34239   //  s0 = -1
34240   //
34241   // fallBB:
34242   //  eax = # XABORT_DEF
34243   //  s1 = eax
34244   //
34245   // sinkMBB:
34246   //  v = phi(s0/mainBB, s1/fallBB)
34247 
34248   MachineBasicBlock *thisMBB = MBB;
34249   MachineFunction *MF = MBB->getParent();
34250   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
34251   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
34252   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
34253   MF->insert(I, mainMBB);
34254   MF->insert(I, fallMBB);
34255   MF->insert(I, sinkMBB);
34256 
34257   if (isEFLAGSLiveAfter(MI, MBB)) {
34258     mainMBB->addLiveIn(X86::EFLAGS);
34259     fallMBB->addLiveIn(X86::EFLAGS);
34260     sinkMBB->addLiveIn(X86::EFLAGS);
34261   }
34262 
34263   // Transfer the remainder of BB and its successor edges to sinkMBB.
34264   sinkMBB->splice(sinkMBB->begin(), MBB,
34265                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
34266   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
34267 
34268   MachineRegisterInfo &MRI = MF->getRegInfo();
34269   Register DstReg = MI.getOperand(0).getReg();
34270   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
34271   Register mainDstReg = MRI.createVirtualRegister(RC);
34272   Register fallDstReg = MRI.createVirtualRegister(RC);
34273 
34274   // thisMBB:
34275   //  xbegin fallMBB
34276   //  # fallthrough to mainMBB
34277   //  # abortion to fallMBB
34278   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
34279   thisMBB->addSuccessor(mainMBB);
34280   thisMBB->addSuccessor(fallMBB);
34281 
34282   // mainMBB:
34283   //  mainDstReg := -1
34284   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
34285   BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
34286   mainMBB->addSuccessor(sinkMBB);
34287 
34288   // fallMBB:
34289   //  ; pseudo instruction to model hardware's definition from XABORT
34290   //  EAX := XABORT_DEF
34291   //  fallDstReg := EAX
34292   BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
34293   BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
34294       .addReg(X86::EAX);
34295   fallMBB->addSuccessor(sinkMBB);
34296 
34297   // sinkMBB:
34298   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
34299   BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
34300       .addReg(mainDstReg).addMBB(mainMBB)
34301       .addReg(fallDstReg).addMBB(fallMBB);
34302 
34303   MI.eraseFromParent();
34304   return sinkMBB;
34305 }
34306 
34307 MachineBasicBlock *
34308 X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
34309                                                MachineBasicBlock *MBB) const {
34310   // Emit va_arg instruction on X86-64.
34311 
34312   // Operands to this pseudo-instruction:
34313   // 0  ) Output        : destination address (reg)
34314   // 1-5) Input         : va_list address (addr, i64mem)
34315   // 6  ) ArgSize       : Size (in bytes) of vararg type
34316   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
34317   // 8  ) Align         : Alignment of type
34318   // 9  ) EFLAGS (implicit-def)
34319 
34320   assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!");
34321   static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
34322 
34323   Register DestReg = MI.getOperand(0).getReg();
34324   MachineOperand &Base = MI.getOperand(1);
34325   MachineOperand &Scale = MI.getOperand(2);
34326   MachineOperand &Index = MI.getOperand(3);
34327   MachineOperand &Disp = MI.getOperand(4);
34328   MachineOperand &Segment = MI.getOperand(5);
34329   unsigned ArgSize = MI.getOperand(6).getImm();
34330   unsigned ArgMode = MI.getOperand(7).getImm();
34331   Align Alignment = Align(MI.getOperand(8).getImm());
34332 
34333   MachineFunction *MF = MBB->getParent();
34334 
34335   // Memory Reference
34336   assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand");
34337 
34338   MachineMemOperand *OldMMO = MI.memoperands().front();
34339 
34340   // Clone the MMO into two separate MMOs for loading and storing
34341   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
34342       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
34343   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
34344       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
34345 
34346   // Machine Information
34347   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34348   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
34349   const TargetRegisterClass *AddrRegClass =
34350       getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
34351   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
34352   const DebugLoc &DL = MI.getDebugLoc();
34353 
34354   // struct va_list {
34355   //   i32   gp_offset
34356   //   i32   fp_offset
34357   //   i64   overflow_area (address)
34358   //   i64   reg_save_area (address)
34359   // }
34360   // sizeof(va_list) = 24
34361   // alignment(va_list) = 8
34362 
34363   unsigned TotalNumIntRegs = 6;
34364   unsigned TotalNumXMMRegs = 8;
34365   bool UseGPOffset = (ArgMode == 1);
34366   bool UseFPOffset = (ArgMode == 2);
34367   unsigned MaxOffset = TotalNumIntRegs * 8 +
34368                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
34369 
34370   /* Align ArgSize to a multiple of 8 */
34371   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
34372   bool NeedsAlign = (Alignment > 8);
34373 
34374   MachineBasicBlock *thisMBB = MBB;
34375   MachineBasicBlock *overflowMBB;
34376   MachineBasicBlock *offsetMBB;
34377   MachineBasicBlock *endMBB;
34378 
34379   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
34380   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
34381   unsigned OffsetReg = 0;
34382 
34383   if (!UseGPOffset && !UseFPOffset) {
34384     // If we only pull from the overflow region, we don't create a branch.
34385     // We don't need to alter control flow.
34386     OffsetDestReg = 0; // unused
34387     OverflowDestReg = DestReg;
34388 
34389     offsetMBB = nullptr;
34390     overflowMBB = thisMBB;
34391     endMBB = thisMBB;
34392   } else {
34393     // First emit code to check if gp_offset (or fp_offset) is below the bound.
34394     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
34395     // If not, pull from overflow_area. (branch to overflowMBB)
34396     //
34397     //       thisMBB
34398     //         |     .
34399     //         |        .
34400     //     offsetMBB   overflowMBB
34401     //         |        .
34402     //         |     .
34403     //        endMBB
34404 
34405     // Registers for the PHI in endMBB
34406     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
34407     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
34408 
34409     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
34410     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34411     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34412     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34413 
34414     MachineFunction::iterator MBBIter = ++MBB->getIterator();
34415 
34416     // Insert the new basic blocks
34417     MF->insert(MBBIter, offsetMBB);
34418     MF->insert(MBBIter, overflowMBB);
34419     MF->insert(MBBIter, endMBB);
34420 
34421     // Transfer the remainder of MBB and its successor edges to endMBB.
34422     endMBB->splice(endMBB->begin(), thisMBB,
34423                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
34424     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
34425 
34426     // Make offsetMBB and overflowMBB successors of thisMBB
34427     thisMBB->addSuccessor(offsetMBB);
34428     thisMBB->addSuccessor(overflowMBB);
34429 
34430     // endMBB is a successor of both offsetMBB and overflowMBB
34431     offsetMBB->addSuccessor(endMBB);
34432     overflowMBB->addSuccessor(endMBB);
34433 
34434     // Load the offset value into a register
34435     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
34436     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
34437         .add(Base)
34438         .add(Scale)
34439         .add(Index)
34440         .addDisp(Disp, UseFPOffset ? 4 : 0)
34441         .add(Segment)
34442         .setMemRefs(LoadOnlyMMO);
34443 
34444     // Check if there is enough room left to pull this argument.
34445     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
34446       .addReg(OffsetReg)
34447       .addImm(MaxOffset + 8 - ArgSizeA8);
34448 
34449     // Branch to "overflowMBB" if offset >= max
34450     // Fall through to "offsetMBB" otherwise
34451     BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
34452       .addMBB(overflowMBB).addImm(X86::COND_AE);
34453   }
34454 
34455   // In offsetMBB, emit code to use the reg_save_area.
34456   if (offsetMBB) {
34457     assert(OffsetReg != 0);
34458 
34459     // Read the reg_save_area address.
34460     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
34461     BuildMI(
34462         offsetMBB, DL,
34463         TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
34464         RegSaveReg)
34465         .add(Base)
34466         .add(Scale)
34467         .add(Index)
34468         .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
34469         .add(Segment)
34470         .setMemRefs(LoadOnlyMMO);
34471 
34472     if (Subtarget.isTarget64BitLP64()) {
34473       // Zero-extend the offset
34474       Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
34475       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
34476           .addImm(0)
34477           .addReg(OffsetReg)
34478           .addImm(X86::sub_32bit);
34479 
34480       // Add the offset to the reg_save_area to get the final address.
34481       BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
34482           .addReg(OffsetReg64)
34483           .addReg(RegSaveReg);
34484     } else {
34485       // Add the offset to the reg_save_area to get the final address.
34486       BuildMI(offsetMBB, DL, TII->get(X86::ADD32rr), OffsetDestReg)
34487           .addReg(OffsetReg)
34488           .addReg(RegSaveReg);
34489     }
34490 
34491     // Compute the offset for the next argument
34492     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
34493     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
34494       .addReg(OffsetReg)
34495       .addImm(UseFPOffset ? 16 : 8);
34496 
34497     // Store it back into the va_list.
34498     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
34499         .add(Base)
34500         .add(Scale)
34501         .add(Index)
34502         .addDisp(Disp, UseFPOffset ? 4 : 0)
34503         .add(Segment)
34504         .addReg(NextOffsetReg)
34505         .setMemRefs(StoreOnlyMMO);
34506 
34507     // Jump to endMBB
34508     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
34509       .addMBB(endMBB);
34510   }
34511 
34512   //
34513   // Emit code to use overflow area
34514   //
34515 
34516   // Load the overflow_area address into a register.
34517   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
34518   BuildMI(overflowMBB, DL,
34519           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
34520           OverflowAddrReg)
34521       .add(Base)
34522       .add(Scale)
34523       .add(Index)
34524       .addDisp(Disp, 8)
34525       .add(Segment)
34526       .setMemRefs(LoadOnlyMMO);
34527 
34528   // If we need to align it, do so. Otherwise, just copy the address
34529   // to OverflowDestReg.
34530   if (NeedsAlign) {
34531     // Align the overflow address
34532     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
34533 
34534     // aligned_addr = (addr + (align-1)) & ~(align-1)
34535     BuildMI(
34536         overflowMBB, DL,
34537         TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
34538         TmpReg)
34539         .addReg(OverflowAddrReg)
34540         .addImm(Alignment.value() - 1);
34541 
34542     BuildMI(
34543         overflowMBB, DL,
34544         TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
34545         OverflowDestReg)
34546         .addReg(TmpReg)
34547         .addImm(~(uint64_t)(Alignment.value() - 1));
34548   } else {
34549     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
34550       .addReg(OverflowAddrReg);
34551   }
34552 
34553   // Compute the next overflow address after this argument.
34554   // (the overflow address should be kept 8-byte aligned)
34555   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
34556   BuildMI(
34557       overflowMBB, DL,
34558       TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
34559       NextAddrReg)
34560       .addReg(OverflowDestReg)
34561       .addImm(ArgSizeA8);
34562 
34563   // Store the new overflow address.
34564   BuildMI(overflowMBB, DL,
34565           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
34566       .add(Base)
34567       .add(Scale)
34568       .add(Index)
34569       .addDisp(Disp, 8)
34570       .add(Segment)
34571       .addReg(NextAddrReg)
34572       .setMemRefs(StoreOnlyMMO);
34573 
34574   // If we branched, emit the PHI to the front of endMBB.
34575   if (offsetMBB) {
34576     BuildMI(*endMBB, endMBB->begin(), DL,
34577             TII->get(X86::PHI), DestReg)
34578       .addReg(OffsetDestReg).addMBB(offsetMBB)
34579       .addReg(OverflowDestReg).addMBB(overflowMBB);
34580   }
34581 
34582   // Erase the pseudo instruction
34583   MI.eraseFromParent();
34584 
34585   return endMBB;
34586 }
34587 
34588 // The EFLAGS operand of SelectItr might be missing a kill marker
34589 // because there were multiple uses of EFLAGS, and ISel didn't know
34590 // which to mark. Figure out whether SelectItr should have had a
34591 // kill marker, and set it if it should. Returns the correct kill
34592 // marker value.
34593 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
34594                                      MachineBasicBlock* BB,
34595                                      const TargetRegisterInfo* TRI) {
34596   if (isEFLAGSLiveAfter(SelectItr, BB))
34597     return false;
34598 
34599   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
34600   // out. SelectMI should have a kill flag on EFLAGS.
34601   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
34602   return true;
34603 }
34604 
34605 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
34606 // together with other CMOV pseudo-opcodes into a single basic-block with
34607 // conditional jump around it.
34608 static bool isCMOVPseudo(MachineInstr &MI) {
34609   switch (MI.getOpcode()) {
34610   case X86::CMOV_FR16:
34611   case X86::CMOV_FR16X:
34612   case X86::CMOV_FR32:
34613   case X86::CMOV_FR32X:
34614   case X86::CMOV_FR64:
34615   case X86::CMOV_FR64X:
34616   case X86::CMOV_GR8:
34617   case X86::CMOV_GR16:
34618   case X86::CMOV_GR32:
34619   case X86::CMOV_RFP32:
34620   case X86::CMOV_RFP64:
34621   case X86::CMOV_RFP80:
34622   case X86::CMOV_VR64:
34623   case X86::CMOV_VR128:
34624   case X86::CMOV_VR128X:
34625   case X86::CMOV_VR256:
34626   case X86::CMOV_VR256X:
34627   case X86::CMOV_VR512:
34628   case X86::CMOV_VK1:
34629   case X86::CMOV_VK2:
34630   case X86::CMOV_VK4:
34631   case X86::CMOV_VK8:
34632   case X86::CMOV_VK16:
34633   case X86::CMOV_VK32:
34634   case X86::CMOV_VK64:
34635     return true;
34636 
34637   default:
34638     return false;
34639   }
34640 }
34641 
34642 // Helper function, which inserts PHI functions into SinkMBB:
34643 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
34644 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
34645 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
34646 // the last PHI function inserted.
34647 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
34648     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
34649     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
34650     MachineBasicBlock *SinkMBB) {
34651   MachineFunction *MF = TrueMBB->getParent();
34652   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
34653   const DebugLoc &DL = MIItBegin->getDebugLoc();
34654 
34655   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
34656   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
34657 
34658   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
34659 
34660   // As we are creating the PHIs, we have to be careful if there is more than
34661   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
34662   // PHIs have to reference the individual true/false inputs from earlier PHIs.
34663   // That also means that PHI construction must work forward from earlier to
34664   // later, and that the code must maintain a mapping from earlier PHI's
34665   // destination registers, and the registers that went into the PHI.
34666   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
34667   MachineInstrBuilder MIB;
34668 
34669   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
34670     Register DestReg = MIIt->getOperand(0).getReg();
34671     Register Op1Reg = MIIt->getOperand(1).getReg();
34672     Register Op2Reg = MIIt->getOperand(2).getReg();
34673 
34674     // If this CMOV we are generating is the opposite condition from
34675     // the jump we generated, then we have to swap the operands for the
34676     // PHI that is going to be generated.
34677     if (MIIt->getOperand(3).getImm() == OppCC)
34678       std::swap(Op1Reg, Op2Reg);
34679 
34680     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
34681       Op1Reg = RegRewriteTable[Op1Reg].first;
34682 
34683     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
34684       Op2Reg = RegRewriteTable[Op2Reg].second;
34685 
34686     MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
34687               .addReg(Op1Reg)
34688               .addMBB(FalseMBB)
34689               .addReg(Op2Reg)
34690               .addMBB(TrueMBB);
34691 
34692     // Add this PHI to the rewrite table.
34693     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
34694   }
34695 
34696   return MIB;
34697 }
34698 
34699 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
34700 MachineBasicBlock *
34701 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
34702                                              MachineInstr &SecondCascadedCMOV,
34703                                              MachineBasicBlock *ThisMBB) const {
34704   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34705   const DebugLoc &DL = FirstCMOV.getDebugLoc();
34706 
34707   // We lower cascaded CMOVs such as
34708   //
34709   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
34710   //
34711   // to two successive branches.
34712   //
34713   // Without this, we would add a PHI between the two jumps, which ends up
34714   // creating a few copies all around. For instance, for
34715   //
34716   //    (sitofp (zext (fcmp une)))
34717   //
34718   // we would generate:
34719   //
34720   //         ucomiss %xmm1, %xmm0
34721   //         movss  <1.0f>, %xmm0
34722   //         movaps  %xmm0, %xmm1
34723   //         jne     .LBB5_2
34724   //         xorps   %xmm1, %xmm1
34725   // .LBB5_2:
34726   //         jp      .LBB5_4
34727   //         movaps  %xmm1, %xmm0
34728   // .LBB5_4:
34729   //         retq
34730   //
34731   // because this custom-inserter would have generated:
34732   //
34733   //   A
34734   //   | \
34735   //   |  B
34736   //   | /
34737   //   C
34738   //   | \
34739   //   |  D
34740   //   | /
34741   //   E
34742   //
34743   // A: X = ...; Y = ...
34744   // B: empty
34745   // C: Z = PHI [X, A], [Y, B]
34746   // D: empty
34747   // E: PHI [X, C], [Z, D]
34748   //
34749   // If we lower both CMOVs in a single step, we can instead generate:
34750   //
34751   //   A
34752   //   | \
34753   //   |  C
34754   //   | /|
34755   //   |/ |
34756   //   |  |
34757   //   |  D
34758   //   | /
34759   //   E
34760   //
34761   // A: X = ...; Y = ...
34762   // D: empty
34763   // E: PHI [X, A], [X, C], [Y, D]
34764   //
34765   // Which, in our sitofp/fcmp example, gives us something like:
34766   //
34767   //         ucomiss %xmm1, %xmm0
34768   //         movss  <1.0f>, %xmm0
34769   //         jne     .LBB5_4
34770   //         jp      .LBB5_4
34771   //         xorps   %xmm0, %xmm0
34772   // .LBB5_4:
34773   //         retq
34774   //
34775 
34776   // We lower cascaded CMOV into two successive branches to the same block.
34777   // EFLAGS is used by both, so mark it as live in the second.
34778   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
34779   MachineFunction *F = ThisMBB->getParent();
34780   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
34781   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
34782   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
34783 
34784   MachineFunction::iterator It = ++ThisMBB->getIterator();
34785   F->insert(It, FirstInsertedMBB);
34786   F->insert(It, SecondInsertedMBB);
34787   F->insert(It, SinkMBB);
34788 
34789   // For a cascaded CMOV, we lower it to two successive branches to
34790   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
34791   // the FirstInsertedMBB.
34792   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
34793 
34794   // If the EFLAGS register isn't dead in the terminator, then claim that it's
34795   // live into the sink and copy blocks.
34796   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
34797   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
34798       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
34799     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
34800     SinkMBB->addLiveIn(X86::EFLAGS);
34801   }
34802 
34803   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
34804   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
34805                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
34806                   ThisMBB->end());
34807   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
34808 
34809   // Fallthrough block for ThisMBB.
34810   ThisMBB->addSuccessor(FirstInsertedMBB);
34811   // The true block target of the first branch is always SinkMBB.
34812   ThisMBB->addSuccessor(SinkMBB);
34813   // Fallthrough block for FirstInsertedMBB.
34814   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
34815   // The true block for the branch of FirstInsertedMBB.
34816   FirstInsertedMBB->addSuccessor(SinkMBB);
34817   // This is fallthrough.
34818   SecondInsertedMBB->addSuccessor(SinkMBB);
34819 
34820   // Create the conditional branch instructions.
34821   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
34822   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
34823 
34824   X86::CondCode SecondCC =
34825       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
34826   BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
34827 
34828   //  SinkMBB:
34829   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
34830   Register DestReg = SecondCascadedCMOV.getOperand(0).getReg();
34831   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
34832   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
34833   MachineInstrBuilder MIB =
34834       BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
34835           .addReg(Op1Reg)
34836           .addMBB(SecondInsertedMBB)
34837           .addReg(Op2Reg)
34838           .addMBB(ThisMBB);
34839 
34840   // The second SecondInsertedMBB provides the same incoming value as the
34841   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
34842   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
34843 
34844   // Now remove the CMOVs.
34845   FirstCMOV.eraseFromParent();
34846   SecondCascadedCMOV.eraseFromParent();
34847 
34848   return SinkMBB;
34849 }
34850 
34851 MachineBasicBlock *
34852 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
34853                                      MachineBasicBlock *ThisMBB) const {
34854   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34855   const DebugLoc &DL = MI.getDebugLoc();
34856 
34857   // To "insert" a SELECT_CC instruction, we actually have to insert the
34858   // diamond control-flow pattern.  The incoming instruction knows the
34859   // destination vreg to set, the condition code register to branch on, the
34860   // true/false values to select between and a branch opcode to use.
34861 
34862   //  ThisMBB:
34863   //  ...
34864   //   TrueVal = ...
34865   //   cmpTY ccX, r1, r2
34866   //   bCC copy1MBB
34867   //   fallthrough --> FalseMBB
34868 
34869   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
34870   // as described above, by inserting a BB, and then making a PHI at the join
34871   // point to select the true and false operands of the CMOV in the PHI.
34872   //
34873   // The code also handles two different cases of multiple CMOV opcodes
34874   // in a row.
34875   //
34876   // Case 1:
34877   // In this case, there are multiple CMOVs in a row, all which are based on
34878   // the same condition setting (or the exact opposite condition setting).
34879   // In this case we can lower all the CMOVs using a single inserted BB, and
34880   // then make a number of PHIs at the join point to model the CMOVs. The only
34881   // trickiness here, is that in a case like:
34882   //
34883   // t2 = CMOV cond1 t1, f1
34884   // t3 = CMOV cond1 t2, f2
34885   //
34886   // when rewriting this into PHIs, we have to perform some renaming on the
34887   // temps since you cannot have a PHI operand refer to a PHI result earlier
34888   // in the same block.  The "simple" but wrong lowering would be:
34889   //
34890   // t2 = PHI t1(BB1), f1(BB2)
34891   // t3 = PHI t2(BB1), f2(BB2)
34892   //
34893   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
34894   // renaming is to note that on the path through BB1, t2 is really just a
34895   // copy of t1, and do that renaming, properly generating:
34896   //
34897   // t2 = PHI t1(BB1), f1(BB2)
34898   // t3 = PHI t1(BB1), f2(BB2)
34899   //
34900   // Case 2:
34901   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
34902   // function - EmitLoweredCascadedSelect.
34903 
34904   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
34905   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
34906   MachineInstr *LastCMOV = &MI;
34907   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
34908 
34909   // Check for case 1, where there are multiple CMOVs with the same condition
34910   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
34911   // number of jumps the most.
34912 
34913   if (isCMOVPseudo(MI)) {
34914     // See if we have a string of CMOVS with the same condition. Skip over
34915     // intervening debug insts.
34916     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
34917            (NextMIIt->getOperand(3).getImm() == CC ||
34918             NextMIIt->getOperand(3).getImm() == OppCC)) {
34919       LastCMOV = &*NextMIIt;
34920       NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
34921     }
34922   }
34923 
34924   // This checks for case 2, but only do this if we didn't already find
34925   // case 1, as indicated by LastCMOV == MI.
34926   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
34927       NextMIIt->getOpcode() == MI.getOpcode() &&
34928       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
34929       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
34930       NextMIIt->getOperand(1).isKill()) {
34931     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
34932   }
34933 
34934   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
34935   MachineFunction *F = ThisMBB->getParent();
34936   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
34937   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
34938 
34939   MachineFunction::iterator It = ++ThisMBB->getIterator();
34940   F->insert(It, FalseMBB);
34941   F->insert(It, SinkMBB);
34942 
34943   // If the EFLAGS register isn't dead in the terminator, then claim that it's
34944   // live into the sink and copy blocks.
34945   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
34946   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
34947       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
34948     FalseMBB->addLiveIn(X86::EFLAGS);
34949     SinkMBB->addLiveIn(X86::EFLAGS);
34950   }
34951 
34952   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
34953   auto DbgRange = llvm::make_range(MachineBasicBlock::iterator(MI),
34954                                    MachineBasicBlock::iterator(LastCMOV));
34955   for (MachineInstr &MI : llvm::make_early_inc_range(DbgRange))
34956     if (MI.isDebugInstr())
34957       SinkMBB->push_back(MI.removeFromParent());
34958 
34959   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
34960   SinkMBB->splice(SinkMBB->end(), ThisMBB,
34961                   std::next(MachineBasicBlock::iterator(LastCMOV)),
34962                   ThisMBB->end());
34963   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
34964 
34965   // Fallthrough block for ThisMBB.
34966   ThisMBB->addSuccessor(FalseMBB);
34967   // The true block target of the first (or only) branch is always a SinkMBB.
34968   ThisMBB->addSuccessor(SinkMBB);
34969   // Fallthrough block for FalseMBB.
34970   FalseMBB->addSuccessor(SinkMBB);
34971 
34972   // Create the conditional branch instruction.
34973   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
34974 
34975   //  SinkMBB:
34976   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
34977   //  ...
34978   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
34979   MachineBasicBlock::iterator MIItEnd =
34980       std::next(MachineBasicBlock::iterator(LastCMOV));
34981   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
34982 
34983   // Now remove the CMOV(s).
34984   ThisMBB->erase(MIItBegin, MIItEnd);
34985 
34986   return SinkMBB;
34987 }
34988 
34989 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
34990   if (IsLP64) {
34991     if (isInt<8>(Imm))
34992       return X86::SUB64ri8;
34993     return X86::SUB64ri32;
34994   } else {
34995     if (isInt<8>(Imm))
34996       return X86::SUB32ri8;
34997     return X86::SUB32ri;
34998   }
34999 }
35000 
35001 MachineBasicBlock *
35002 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
35003                                            MachineBasicBlock *MBB) const {
35004   MachineFunction *MF = MBB->getParent();
35005   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35006   const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
35007   const DebugLoc &DL = MI.getDebugLoc();
35008   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
35009 
35010   const unsigned ProbeSize = getStackProbeSize(*MF);
35011 
35012   MachineRegisterInfo &MRI = MF->getRegInfo();
35013   MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35014   MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35015   MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35016 
35017   MachineFunction::iterator MBBIter = ++MBB->getIterator();
35018   MF->insert(MBBIter, testMBB);
35019   MF->insert(MBBIter, blockMBB);
35020   MF->insert(MBBIter, tailMBB);
35021 
35022   Register sizeVReg = MI.getOperand(1).getReg();
35023 
35024   Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
35025 
35026   Register TmpStackPtr = MRI.createVirtualRegister(
35027       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
35028   Register FinalStackPtr = MRI.createVirtualRegister(
35029       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
35030 
35031   BuildMI(*MBB, {MI}, DL, TII->get(TargetOpcode::COPY), TmpStackPtr)
35032       .addReg(physSPReg);
35033   {
35034     const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
35035     BuildMI(*MBB, {MI}, DL, TII->get(Opc), FinalStackPtr)
35036         .addReg(TmpStackPtr)
35037         .addReg(sizeVReg);
35038   }
35039 
35040   // test rsp size
35041 
35042   BuildMI(testMBB, DL,
35043           TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
35044       .addReg(FinalStackPtr)
35045       .addReg(physSPReg);
35046 
35047   BuildMI(testMBB, DL, TII->get(X86::JCC_1))
35048       .addMBB(tailMBB)
35049       .addImm(X86::COND_GE);
35050   testMBB->addSuccessor(blockMBB);
35051   testMBB->addSuccessor(tailMBB);
35052 
35053   // Touch the block then extend it. This is done on the opposite side of
35054   // static probe where we allocate then touch, to avoid the need of probing the
35055   // tail of the static alloca. Possible scenarios are:
35056   //
35057   //       + ---- <- ------------ <- ------------- <- ------------ +
35058   //       |                                                       |
35059   // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
35060   //                                                               |                                                               |
35061   //                                                               + <- ----------- <- ------------ <- ----------- <- ------------ +
35062   //
35063   // The property we want to enforce is to never have more than [page alloc] between two probes.
35064 
35065   const unsigned XORMIOpc =
35066       TFI.Uses64BitFramePtr ? X86::XOR64mi8 : X86::XOR32mi8;
35067   addRegOffset(BuildMI(blockMBB, DL, TII->get(XORMIOpc)), physSPReg, false, 0)
35068       .addImm(0);
35069 
35070   BuildMI(blockMBB, DL,
35071           TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr, ProbeSize)), physSPReg)
35072       .addReg(physSPReg)
35073       .addImm(ProbeSize);
35074 
35075 
35076   BuildMI(blockMBB, DL, TII->get(X86::JMP_1)).addMBB(testMBB);
35077   blockMBB->addSuccessor(testMBB);
35078 
35079   // Replace original instruction by the expected stack ptr
35080   BuildMI(tailMBB, DL, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
35081       .addReg(FinalStackPtr);
35082 
35083   tailMBB->splice(tailMBB->end(), MBB,
35084                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
35085   tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
35086   MBB->addSuccessor(testMBB);
35087 
35088   // Delete the original pseudo instruction.
35089   MI.eraseFromParent();
35090 
35091   // And we're done.
35092   return tailMBB;
35093 }
35094 
35095 MachineBasicBlock *
35096 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
35097                                         MachineBasicBlock *BB) const {
35098   MachineFunction *MF = BB->getParent();
35099   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35100   const DebugLoc &DL = MI.getDebugLoc();
35101   const BasicBlock *LLVM_BB = BB->getBasicBlock();
35102 
35103   assert(MF->shouldSplitStack());
35104 
35105   const bool Is64Bit = Subtarget.is64Bit();
35106   const bool IsLP64 = Subtarget.isTarget64BitLP64();
35107 
35108   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
35109   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
35110 
35111   // BB:
35112   //  ... [Till the alloca]
35113   // If stacklet is not large enough, jump to mallocMBB
35114   //
35115   // bumpMBB:
35116   //  Allocate by subtracting from RSP
35117   //  Jump to continueMBB
35118   //
35119   // mallocMBB:
35120   //  Allocate by call to runtime
35121   //
35122   // continueMBB:
35123   //  ...
35124   //  [rest of original BB]
35125   //
35126 
35127   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35128   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35129   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35130 
35131   MachineRegisterInfo &MRI = MF->getRegInfo();
35132   const TargetRegisterClass *AddrRegClass =
35133       getRegClassFor(getPointerTy(MF->getDataLayout()));
35134 
35135   Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
35136            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
35137            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
35138            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
35139            sizeVReg = MI.getOperand(1).getReg(),
35140            physSPReg =
35141                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
35142 
35143   MachineFunction::iterator MBBIter = ++BB->getIterator();
35144 
35145   MF->insert(MBBIter, bumpMBB);
35146   MF->insert(MBBIter, mallocMBB);
35147   MF->insert(MBBIter, continueMBB);
35148 
35149   continueMBB->splice(continueMBB->begin(), BB,
35150                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
35151   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
35152 
35153   // Add code to the main basic block to check if the stack limit has been hit,
35154   // and if so, jump to mallocMBB otherwise to bumpMBB.
35155   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
35156   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
35157     .addReg(tmpSPVReg).addReg(sizeVReg);
35158   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
35159     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
35160     .addReg(SPLimitVReg);
35161   BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
35162 
35163   // bumpMBB simply decreases the stack pointer, since we know the current
35164   // stacklet has enough space.
35165   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
35166     .addReg(SPLimitVReg);
35167   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
35168     .addReg(SPLimitVReg);
35169   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
35170 
35171   // Calls into a routine in libgcc to allocate more space from the heap.
35172   const uint32_t *RegMask =
35173       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
35174   if (IsLP64) {
35175     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
35176       .addReg(sizeVReg);
35177     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
35178       .addExternalSymbol("__morestack_allocate_stack_space")
35179       .addRegMask(RegMask)
35180       .addReg(X86::RDI, RegState::Implicit)
35181       .addReg(X86::RAX, RegState::ImplicitDefine);
35182   } else if (Is64Bit) {
35183     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
35184       .addReg(sizeVReg);
35185     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
35186       .addExternalSymbol("__morestack_allocate_stack_space")
35187       .addRegMask(RegMask)
35188       .addReg(X86::EDI, RegState::Implicit)
35189       .addReg(X86::EAX, RegState::ImplicitDefine);
35190   } else {
35191     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
35192       .addImm(12);
35193     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
35194     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
35195       .addExternalSymbol("__morestack_allocate_stack_space")
35196       .addRegMask(RegMask)
35197       .addReg(X86::EAX, RegState::ImplicitDefine);
35198   }
35199 
35200   if (!Is64Bit)
35201     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
35202       .addImm(16);
35203 
35204   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
35205     .addReg(IsLP64 ? X86::RAX : X86::EAX);
35206   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
35207 
35208   // Set up the CFG correctly.
35209   BB->addSuccessor(bumpMBB);
35210   BB->addSuccessor(mallocMBB);
35211   mallocMBB->addSuccessor(continueMBB);
35212   bumpMBB->addSuccessor(continueMBB);
35213 
35214   // Take care of the PHI nodes.
35215   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
35216           MI.getOperand(0).getReg())
35217       .addReg(mallocPtrVReg)
35218       .addMBB(mallocMBB)
35219       .addReg(bumpSPPtrVReg)
35220       .addMBB(bumpMBB);
35221 
35222   // Delete the original pseudo instruction.
35223   MI.eraseFromParent();
35224 
35225   // And we're done.
35226   return continueMBB;
35227 }
35228 
35229 MachineBasicBlock *
35230 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
35231                                        MachineBasicBlock *BB) const {
35232   MachineFunction *MF = BB->getParent();
35233   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
35234   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
35235   const DebugLoc &DL = MI.getDebugLoc();
35236 
35237   assert(!isAsynchronousEHPersonality(
35238              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
35239          "SEH does not use catchret!");
35240 
35241   // Only 32-bit EH needs to worry about manually restoring stack pointers.
35242   if (!Subtarget.is32Bit())
35243     return BB;
35244 
35245   // C++ EH creates a new target block to hold the restore code, and wires up
35246   // the new block to the return destination with a normal JMP_4.
35247   MachineBasicBlock *RestoreMBB =
35248       MF->CreateMachineBasicBlock(BB->getBasicBlock());
35249   assert(BB->succ_size() == 1);
35250   MF->insert(std::next(BB->getIterator()), RestoreMBB);
35251   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
35252   BB->addSuccessor(RestoreMBB);
35253   MI.getOperand(0).setMBB(RestoreMBB);
35254 
35255   // Marking this as an EH pad but not a funclet entry block causes PEI to
35256   // restore stack pointers in the block.
35257   RestoreMBB->setIsEHPad(true);
35258 
35259   auto RestoreMBBI = RestoreMBB->begin();
35260   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
35261   return BB;
35262 }
35263 
35264 MachineBasicBlock *
35265 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
35266                                       MachineBasicBlock *BB) const {
35267   // So, here we replace TLSADDR with the sequence:
35268   // adjust_stackdown -> TLSADDR -> adjust_stackup.
35269   // We need this because TLSADDR is lowered into calls
35270   // inside MC, therefore without the two markers shrink-wrapping
35271   // may push the prologue/epilogue pass them.
35272   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
35273   const DebugLoc &DL = MI.getDebugLoc();
35274   MachineFunction &MF = *BB->getParent();
35275 
35276   // Emit CALLSEQ_START right before the instruction.
35277   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
35278   MachineInstrBuilder CallseqStart =
35279     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
35280   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
35281 
35282   // Emit CALLSEQ_END right after the instruction.
35283   // We don't call erase from parent because we want to keep the
35284   // original instruction around.
35285   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
35286   MachineInstrBuilder CallseqEnd =
35287     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
35288   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
35289 
35290   return BB;
35291 }
35292 
35293 MachineBasicBlock *
35294 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
35295                                       MachineBasicBlock *BB) const {
35296   // This is pretty easy.  We're taking the value that we received from
35297   // our load from the relocation, sticking it in either RDI (x86-64)
35298   // or EAX and doing an indirect call.  The return value will then
35299   // be in the normal return register.
35300   MachineFunction *F = BB->getParent();
35301   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35302   const DebugLoc &DL = MI.getDebugLoc();
35303 
35304   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
35305   assert(MI.getOperand(3).isGlobal() && "This should be a global");
35306 
35307   // Get a register mask for the lowered call.
35308   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
35309   // proper register mask.
35310   const uint32_t *RegMask =
35311       Subtarget.is64Bit() ?
35312       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
35313       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
35314   if (Subtarget.is64Bit()) {
35315     MachineInstrBuilder MIB =
35316         BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
35317             .addReg(X86::RIP)
35318             .addImm(0)
35319             .addReg(0)
35320             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
35321                               MI.getOperand(3).getTargetFlags())
35322             .addReg(0);
35323     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
35324     addDirectMem(MIB, X86::RDI);
35325     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
35326   } else if (!isPositionIndependent()) {
35327     MachineInstrBuilder MIB =
35328         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
35329             .addReg(0)
35330             .addImm(0)
35331             .addReg(0)
35332             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
35333                               MI.getOperand(3).getTargetFlags())
35334             .addReg(0);
35335     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
35336     addDirectMem(MIB, X86::EAX);
35337     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
35338   } else {
35339     MachineInstrBuilder MIB =
35340         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
35341             .addReg(TII->getGlobalBaseReg(F))
35342             .addImm(0)
35343             .addReg(0)
35344             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
35345                               MI.getOperand(3).getTargetFlags())
35346             .addReg(0);
35347     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
35348     addDirectMem(MIB, X86::EAX);
35349     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
35350   }
35351 
35352   MI.eraseFromParent(); // The pseudo instruction is gone now.
35353   return BB;
35354 }
35355 
35356 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
35357   switch (RPOpc) {
35358   case X86::INDIRECT_THUNK_CALL32:
35359     return X86::CALLpcrel32;
35360   case X86::INDIRECT_THUNK_CALL64:
35361     return X86::CALL64pcrel32;
35362   case X86::INDIRECT_THUNK_TCRETURN32:
35363     return X86::TCRETURNdi;
35364   case X86::INDIRECT_THUNK_TCRETURN64:
35365     return X86::TCRETURNdi64;
35366   }
35367   llvm_unreachable("not indirect thunk opcode");
35368 }
35369 
35370 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
35371                                           unsigned Reg) {
35372   if (Subtarget.useRetpolineExternalThunk()) {
35373     // When using an external thunk for retpolines, we pick names that match the
35374     // names GCC happens to use as well. This helps simplify the implementation
35375     // of the thunks for kernels where they have no easy ability to create
35376     // aliases and are doing non-trivial configuration of the thunk's body. For
35377     // example, the Linux kernel will do boot-time hot patching of the thunk
35378     // bodies and cannot easily export aliases of these to loaded modules.
35379     //
35380     // Note that at any point in the future, we may need to change the semantics
35381     // of how we implement retpolines and at that time will likely change the
35382     // name of the called thunk. Essentially, there is no hard guarantee that
35383     // LLVM will generate calls to specific thunks, we merely make a best-effort
35384     // attempt to help out kernels and other systems where duplicating the
35385     // thunks is costly.
35386     switch (Reg) {
35387     case X86::EAX:
35388       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35389       return "__x86_indirect_thunk_eax";
35390     case X86::ECX:
35391       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35392       return "__x86_indirect_thunk_ecx";
35393     case X86::EDX:
35394       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35395       return "__x86_indirect_thunk_edx";
35396     case X86::EDI:
35397       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35398       return "__x86_indirect_thunk_edi";
35399     case X86::R11:
35400       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
35401       return "__x86_indirect_thunk_r11";
35402     }
35403     llvm_unreachable("unexpected reg for external indirect thunk");
35404   }
35405 
35406   if (Subtarget.useRetpolineIndirectCalls() ||
35407       Subtarget.useRetpolineIndirectBranches()) {
35408     // When targeting an internal COMDAT thunk use an LLVM-specific name.
35409     switch (Reg) {
35410     case X86::EAX:
35411       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35412       return "__llvm_retpoline_eax";
35413     case X86::ECX:
35414       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35415       return "__llvm_retpoline_ecx";
35416     case X86::EDX:
35417       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35418       return "__llvm_retpoline_edx";
35419     case X86::EDI:
35420       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35421       return "__llvm_retpoline_edi";
35422     case X86::R11:
35423       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
35424       return "__llvm_retpoline_r11";
35425     }
35426     llvm_unreachable("unexpected reg for retpoline");
35427   }
35428 
35429   if (Subtarget.useLVIControlFlowIntegrity()) {
35430     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
35431     return "__llvm_lvi_thunk_r11";
35432   }
35433   llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
35434 }
35435 
35436 MachineBasicBlock *
35437 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
35438                                             MachineBasicBlock *BB) const {
35439   // Copy the virtual register into the R11 physical register and
35440   // call the retpoline thunk.
35441   const DebugLoc &DL = MI.getDebugLoc();
35442   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35443   Register CalleeVReg = MI.getOperand(0).getReg();
35444   unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
35445 
35446   // Find an available scratch register to hold the callee. On 64-bit, we can
35447   // just use R11, but we scan for uses anyway to ensure we don't generate
35448   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
35449   // already a register use operand to the call to hold the callee. If none
35450   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
35451   // register and ESI is the base pointer to realigned stack frames with VLAs.
35452   SmallVector<unsigned, 3> AvailableRegs;
35453   if (Subtarget.is64Bit())
35454     AvailableRegs.push_back(X86::R11);
35455   else
35456     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
35457 
35458   // Zero out any registers that are already used.
35459   for (const auto &MO : MI.operands()) {
35460     if (MO.isReg() && MO.isUse())
35461       for (unsigned &Reg : AvailableRegs)
35462         if (Reg == MO.getReg())
35463           Reg = 0;
35464   }
35465 
35466   // Choose the first remaining non-zero available register.
35467   unsigned AvailableReg = 0;
35468   for (unsigned MaybeReg : AvailableRegs) {
35469     if (MaybeReg) {
35470       AvailableReg = MaybeReg;
35471       break;
35472     }
35473   }
35474   if (!AvailableReg)
35475     report_fatal_error("calling convention incompatible with retpoline, no "
35476                        "available registers");
35477 
35478   const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
35479 
35480   BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
35481       .addReg(CalleeVReg);
35482   MI.getOperand(0).ChangeToES(Symbol);
35483   MI.setDesc(TII->get(Opc));
35484   MachineInstrBuilder(*BB->getParent(), &MI)
35485       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
35486   return BB;
35487 }
35488 
35489 /// SetJmp implies future control flow change upon calling the corresponding
35490 /// LongJmp.
35491 /// Instead of using the 'return' instruction, the long jump fixes the stack and
35492 /// performs an indirect branch. To do so it uses the registers that were stored
35493 /// in the jump buffer (when calling SetJmp).
35494 /// In case the shadow stack is enabled we need to fix it as well, because some
35495 /// return addresses will be skipped.
35496 /// The function will save the SSP for future fixing in the function
35497 /// emitLongJmpShadowStackFix.
35498 /// \sa emitLongJmpShadowStackFix
35499 /// \param [in] MI The temporary Machine Instruction for the builtin.
35500 /// \param [in] MBB The Machine Basic Block that will be modified.
35501 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
35502                                                  MachineBasicBlock *MBB) const {
35503   const DebugLoc &DL = MI.getDebugLoc();
35504   MachineFunction *MF = MBB->getParent();
35505   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35506   MachineRegisterInfo &MRI = MF->getRegInfo();
35507   MachineInstrBuilder MIB;
35508 
35509   // Memory Reference.
35510   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35511                                            MI.memoperands_end());
35512 
35513   // Initialize a register with zero.
35514   MVT PVT = getPointerTy(MF->getDataLayout());
35515   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
35516   Register ZReg = MRI.createVirtualRegister(PtrRC);
35517   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
35518   BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
35519       .addDef(ZReg)
35520       .addReg(ZReg, RegState::Undef)
35521       .addReg(ZReg, RegState::Undef);
35522 
35523   // Read the current SSP Register value to the zeroed register.
35524   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
35525   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
35526   BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
35527 
35528   // Write the SSP register value to offset 3 in input memory buffer.
35529   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35530   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
35531   const int64_t SSPOffset = 3 * PVT.getStoreSize();
35532   const unsigned MemOpndSlot = 1;
35533   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35534     if (i == X86::AddrDisp)
35535       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
35536     else
35537       MIB.add(MI.getOperand(MemOpndSlot + i));
35538   }
35539   MIB.addReg(SSPCopyReg);
35540   MIB.setMemRefs(MMOs);
35541 }
35542 
35543 MachineBasicBlock *
35544 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
35545                                     MachineBasicBlock *MBB) const {
35546   const DebugLoc &DL = MI.getDebugLoc();
35547   MachineFunction *MF = MBB->getParent();
35548   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35549   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
35550   MachineRegisterInfo &MRI = MF->getRegInfo();
35551 
35552   const BasicBlock *BB = MBB->getBasicBlock();
35553   MachineFunction::iterator I = ++MBB->getIterator();
35554 
35555   // Memory Reference
35556   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35557                                            MI.memoperands_end());
35558 
35559   unsigned DstReg;
35560   unsigned MemOpndSlot = 0;
35561 
35562   unsigned CurOp = 0;
35563 
35564   DstReg = MI.getOperand(CurOp++).getReg();
35565   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
35566   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
35567   (void)TRI;
35568   Register mainDstReg = MRI.createVirtualRegister(RC);
35569   Register restoreDstReg = MRI.createVirtualRegister(RC);
35570 
35571   MemOpndSlot = CurOp;
35572 
35573   MVT PVT = getPointerTy(MF->getDataLayout());
35574   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
35575          "Invalid Pointer Size!");
35576 
35577   // For v = setjmp(buf), we generate
35578   //
35579   // thisMBB:
35580   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
35581   //  SjLjSetup restoreMBB
35582   //
35583   // mainMBB:
35584   //  v_main = 0
35585   //
35586   // sinkMBB:
35587   //  v = phi(main, restore)
35588   //
35589   // restoreMBB:
35590   //  if base pointer being used, load it from frame
35591   //  v_restore = 1
35592 
35593   MachineBasicBlock *thisMBB = MBB;
35594   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
35595   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
35596   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
35597   MF->insert(I, mainMBB);
35598   MF->insert(I, sinkMBB);
35599   MF->push_back(restoreMBB);
35600   restoreMBB->setHasAddressTaken();
35601 
35602   MachineInstrBuilder MIB;
35603 
35604   // Transfer the remainder of BB and its successor edges to sinkMBB.
35605   sinkMBB->splice(sinkMBB->begin(), MBB,
35606                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
35607   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
35608 
35609   // thisMBB:
35610   unsigned PtrStoreOpc = 0;
35611   unsigned LabelReg = 0;
35612   const int64_t LabelOffset = 1 * PVT.getStoreSize();
35613   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
35614                      !isPositionIndependent();
35615 
35616   // Prepare IP either in reg or imm.
35617   if (!UseImmLabel) {
35618     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35619     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
35620     LabelReg = MRI.createVirtualRegister(PtrRC);
35621     if (Subtarget.is64Bit()) {
35622       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
35623               .addReg(X86::RIP)
35624               .addImm(0)
35625               .addReg(0)
35626               .addMBB(restoreMBB)
35627               .addReg(0);
35628     } else {
35629       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
35630       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
35631               .addReg(XII->getGlobalBaseReg(MF))
35632               .addImm(0)
35633               .addReg(0)
35634               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
35635               .addReg(0);
35636     }
35637   } else
35638     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
35639   // Store IP
35640   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
35641   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35642     if (i == X86::AddrDisp)
35643       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
35644     else
35645       MIB.add(MI.getOperand(MemOpndSlot + i));
35646   }
35647   if (!UseImmLabel)
35648     MIB.addReg(LabelReg);
35649   else
35650     MIB.addMBB(restoreMBB);
35651   MIB.setMemRefs(MMOs);
35652 
35653   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
35654     emitSetJmpShadowStackFix(MI, thisMBB);
35655   }
35656 
35657   // Setup
35658   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
35659           .addMBB(restoreMBB);
35660 
35661   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
35662   MIB.addRegMask(RegInfo->getNoPreservedMask());
35663   thisMBB->addSuccessor(mainMBB);
35664   thisMBB->addSuccessor(restoreMBB);
35665 
35666   // mainMBB:
35667   //  EAX = 0
35668   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
35669   mainMBB->addSuccessor(sinkMBB);
35670 
35671   // sinkMBB:
35672   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
35673           TII->get(X86::PHI), DstReg)
35674     .addReg(mainDstReg).addMBB(mainMBB)
35675     .addReg(restoreDstReg).addMBB(restoreMBB);
35676 
35677   // restoreMBB:
35678   if (RegInfo->hasBasePointer(*MF)) {
35679     const bool Uses64BitFramePtr =
35680         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
35681     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
35682     X86FI->setRestoreBasePointer(MF);
35683     Register FramePtr = RegInfo->getFrameRegister(*MF);
35684     Register BasePtr = RegInfo->getBaseRegister();
35685     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
35686     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
35687                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
35688       .setMIFlag(MachineInstr::FrameSetup);
35689   }
35690   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
35691   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
35692   restoreMBB->addSuccessor(sinkMBB);
35693 
35694   MI.eraseFromParent();
35695   return sinkMBB;
35696 }
35697 
35698 /// Fix the shadow stack using the previously saved SSP pointer.
35699 /// \sa emitSetJmpShadowStackFix
35700 /// \param [in] MI The temporary Machine Instruction for the builtin.
35701 /// \param [in] MBB The Machine Basic Block that will be modified.
35702 /// \return The sink MBB that will perform the future indirect branch.
35703 MachineBasicBlock *
35704 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
35705                                              MachineBasicBlock *MBB) const {
35706   const DebugLoc &DL = MI.getDebugLoc();
35707   MachineFunction *MF = MBB->getParent();
35708   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35709   MachineRegisterInfo &MRI = MF->getRegInfo();
35710 
35711   // Memory Reference
35712   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35713                                            MI.memoperands_end());
35714 
35715   MVT PVT = getPointerTy(MF->getDataLayout());
35716   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
35717 
35718   // checkSspMBB:
35719   //         xor vreg1, vreg1
35720   //         rdssp vreg1
35721   //         test vreg1, vreg1
35722   //         je sinkMBB   # Jump if Shadow Stack is not supported
35723   // fallMBB:
35724   //         mov buf+24/12(%rip), vreg2
35725   //         sub vreg1, vreg2
35726   //         jbe sinkMBB  # No need to fix the Shadow Stack
35727   // fixShadowMBB:
35728   //         shr 3/2, vreg2
35729   //         incssp vreg2  # fix the SSP according to the lower 8 bits
35730   //         shr 8, vreg2
35731   //         je sinkMBB
35732   // fixShadowLoopPrepareMBB:
35733   //         shl vreg2
35734   //         mov 128, vreg3
35735   // fixShadowLoopMBB:
35736   //         incssp vreg3
35737   //         dec vreg2
35738   //         jne fixShadowLoopMBB # Iterate until you finish fixing
35739   //                              # the Shadow Stack
35740   // sinkMBB:
35741 
35742   MachineFunction::iterator I = ++MBB->getIterator();
35743   const BasicBlock *BB = MBB->getBasicBlock();
35744 
35745   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
35746   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
35747   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
35748   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
35749   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
35750   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
35751   MF->insert(I, checkSspMBB);
35752   MF->insert(I, fallMBB);
35753   MF->insert(I, fixShadowMBB);
35754   MF->insert(I, fixShadowLoopPrepareMBB);
35755   MF->insert(I, fixShadowLoopMBB);
35756   MF->insert(I, sinkMBB);
35757 
35758   // Transfer the remainder of BB and its successor edges to sinkMBB.
35759   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
35760                   MBB->end());
35761   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
35762 
35763   MBB->addSuccessor(checkSspMBB);
35764 
35765   // Initialize a register with zero.
35766   Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
35767   BuildMI(checkSspMBB, DL, TII->get(X86::MOV32r0), ZReg);
35768 
35769   if (PVT == MVT::i64) {
35770     Register TmpZReg = MRI.createVirtualRegister(PtrRC);
35771     BuildMI(checkSspMBB, DL, TII->get(X86::SUBREG_TO_REG), TmpZReg)
35772       .addImm(0)
35773       .addReg(ZReg)
35774       .addImm(X86::sub_32bit);
35775     ZReg = TmpZReg;
35776   }
35777 
35778   // Read the current SSP Register value to the zeroed register.
35779   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
35780   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
35781   BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
35782 
35783   // Check whether the result of the SSP register is zero and jump directly
35784   // to the sink.
35785   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
35786   BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
35787       .addReg(SSPCopyReg)
35788       .addReg(SSPCopyReg);
35789   BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
35790   checkSspMBB->addSuccessor(sinkMBB);
35791   checkSspMBB->addSuccessor(fallMBB);
35792 
35793   // Reload the previously saved SSP register value.
35794   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
35795   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
35796   const int64_t SPPOffset = 3 * PVT.getStoreSize();
35797   MachineInstrBuilder MIB =
35798       BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
35799   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35800     const MachineOperand &MO = MI.getOperand(i);
35801     if (i == X86::AddrDisp)
35802       MIB.addDisp(MO, SPPOffset);
35803     else if (MO.isReg()) // Don't add the whole operand, we don't want to
35804                          // preserve kill flags.
35805       MIB.addReg(MO.getReg());
35806     else
35807       MIB.add(MO);
35808   }
35809   MIB.setMemRefs(MMOs);
35810 
35811   // Subtract the current SSP from the previous SSP.
35812   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
35813   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
35814   BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
35815       .addReg(PrevSSPReg)
35816       .addReg(SSPCopyReg);
35817 
35818   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
35819   BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
35820   fallMBB->addSuccessor(sinkMBB);
35821   fallMBB->addSuccessor(fixShadowMBB);
35822 
35823   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
35824   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
35825   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
35826   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
35827   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
35828       .addReg(SspSubReg)
35829       .addImm(Offset);
35830 
35831   // Increase SSP when looking only on the lower 8 bits of the delta.
35832   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
35833   BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
35834 
35835   // Reset the lower 8 bits.
35836   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
35837   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
35838       .addReg(SspFirstShrReg)
35839       .addImm(8);
35840 
35841   // Jump if the result of the shift is zero.
35842   BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
35843   fixShadowMBB->addSuccessor(sinkMBB);
35844   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
35845 
35846   // Do a single shift left.
35847   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
35848   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
35849   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
35850       .addReg(SspSecondShrReg);
35851 
35852   // Save the value 128 to a register (will be used next with incssp).
35853   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
35854   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
35855   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
35856       .addImm(128);
35857   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
35858 
35859   // Since incssp only looks at the lower 8 bits, we might need to do several
35860   // iterations of incssp until we finish fixing the shadow stack.
35861   Register DecReg = MRI.createVirtualRegister(PtrRC);
35862   Register CounterReg = MRI.createVirtualRegister(PtrRC);
35863   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
35864       .addReg(SspAfterShlReg)
35865       .addMBB(fixShadowLoopPrepareMBB)
35866       .addReg(DecReg)
35867       .addMBB(fixShadowLoopMBB);
35868 
35869   // Every iteration we increase the SSP by 128.
35870   BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
35871 
35872   // Every iteration we decrement the counter by 1.
35873   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
35874   BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
35875 
35876   // Jump if the counter is not zero yet.
35877   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
35878   fixShadowLoopMBB->addSuccessor(sinkMBB);
35879   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
35880 
35881   return sinkMBB;
35882 }
35883 
35884 MachineBasicBlock *
35885 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
35886                                      MachineBasicBlock *MBB) const {
35887   const DebugLoc &DL = MI.getDebugLoc();
35888   MachineFunction *MF = MBB->getParent();
35889   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35890   MachineRegisterInfo &MRI = MF->getRegInfo();
35891 
35892   // Memory Reference
35893   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35894                                            MI.memoperands_end());
35895 
35896   MVT PVT = getPointerTy(MF->getDataLayout());
35897   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
35898          "Invalid Pointer Size!");
35899 
35900   const TargetRegisterClass *RC =
35901     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
35902   Register Tmp = MRI.createVirtualRegister(RC);
35903   // Since FP is only updated here but NOT referenced, it's treated as GPR.
35904   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
35905   Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
35906   Register SP = RegInfo->getStackRegister();
35907 
35908   MachineInstrBuilder MIB;
35909 
35910   const int64_t LabelOffset = 1 * PVT.getStoreSize();
35911   const int64_t SPOffset = 2 * PVT.getStoreSize();
35912 
35913   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
35914   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
35915 
35916   MachineBasicBlock *thisMBB = MBB;
35917 
35918   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
35919   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
35920     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
35921   }
35922 
35923   // Reload FP
35924   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
35925   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35926     const MachineOperand &MO = MI.getOperand(i);
35927     if (MO.isReg()) // Don't add the whole operand, we don't want to
35928                     // preserve kill flags.
35929       MIB.addReg(MO.getReg());
35930     else
35931       MIB.add(MO);
35932   }
35933   MIB.setMemRefs(MMOs);
35934 
35935   // Reload IP
35936   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
35937   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35938     const MachineOperand &MO = MI.getOperand(i);
35939     if (i == X86::AddrDisp)
35940       MIB.addDisp(MO, LabelOffset);
35941     else if (MO.isReg()) // Don't add the whole operand, we don't want to
35942                          // preserve kill flags.
35943       MIB.addReg(MO.getReg());
35944     else
35945       MIB.add(MO);
35946   }
35947   MIB.setMemRefs(MMOs);
35948 
35949   // Reload SP
35950   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
35951   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35952     if (i == X86::AddrDisp)
35953       MIB.addDisp(MI.getOperand(i), SPOffset);
35954     else
35955       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
35956                                  // the last instruction of the expansion.
35957   }
35958   MIB.setMemRefs(MMOs);
35959 
35960   // Jump
35961   BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
35962 
35963   MI.eraseFromParent();
35964   return thisMBB;
35965 }
35966 
35967 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
35968                                                MachineBasicBlock *MBB,
35969                                                MachineBasicBlock *DispatchBB,
35970                                                int FI) const {
35971   const DebugLoc &DL = MI.getDebugLoc();
35972   MachineFunction *MF = MBB->getParent();
35973   MachineRegisterInfo *MRI = &MF->getRegInfo();
35974   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35975 
35976   MVT PVT = getPointerTy(MF->getDataLayout());
35977   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
35978 
35979   unsigned Op = 0;
35980   unsigned VR = 0;
35981 
35982   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
35983                      !isPositionIndependent();
35984 
35985   if (UseImmLabel) {
35986     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
35987   } else {
35988     const TargetRegisterClass *TRC =
35989         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
35990     VR = MRI->createVirtualRegister(TRC);
35991     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35992 
35993     if (Subtarget.is64Bit())
35994       BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
35995           .addReg(X86::RIP)
35996           .addImm(1)
35997           .addReg(0)
35998           .addMBB(DispatchBB)
35999           .addReg(0);
36000     else
36001       BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
36002           .addReg(0) /* TII->getGlobalBaseReg(MF) */
36003           .addImm(1)
36004           .addReg(0)
36005           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
36006           .addReg(0);
36007   }
36008 
36009   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
36010   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
36011   if (UseImmLabel)
36012     MIB.addMBB(DispatchBB);
36013   else
36014     MIB.addReg(VR);
36015 }
36016 
36017 MachineBasicBlock *
36018 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
36019                                          MachineBasicBlock *BB) const {
36020   const DebugLoc &DL = MI.getDebugLoc();
36021   MachineFunction *MF = BB->getParent();
36022   MachineRegisterInfo *MRI = &MF->getRegInfo();
36023   const X86InstrInfo *TII = Subtarget.getInstrInfo();
36024   int FI = MF->getFrameInfo().getFunctionContextIndex();
36025 
36026   // Get a mapping of the call site numbers to all of the landing pads they're
36027   // associated with.
36028   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
36029   unsigned MaxCSNum = 0;
36030   for (auto &MBB : *MF) {
36031     if (!MBB.isEHPad())
36032       continue;
36033 
36034     MCSymbol *Sym = nullptr;
36035     for (const auto &MI : MBB) {
36036       if (MI.isDebugInstr())
36037         continue;
36038 
36039       assert(MI.isEHLabel() && "expected EH_LABEL");
36040       Sym = MI.getOperand(0).getMCSymbol();
36041       break;
36042     }
36043 
36044     if (!MF->hasCallSiteLandingPad(Sym))
36045       continue;
36046 
36047     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
36048       CallSiteNumToLPad[CSI].push_back(&MBB);
36049       MaxCSNum = std::max(MaxCSNum, CSI);
36050     }
36051   }
36052 
36053   // Get an ordered list of the machine basic blocks for the jump table.
36054   std::vector<MachineBasicBlock *> LPadList;
36055   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
36056   LPadList.reserve(CallSiteNumToLPad.size());
36057 
36058   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
36059     for (auto &LP : CallSiteNumToLPad[CSI]) {
36060       LPadList.push_back(LP);
36061       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
36062     }
36063   }
36064 
36065   assert(!LPadList.empty() &&
36066          "No landing pad destinations for the dispatch jump table!");
36067 
36068   // Create the MBBs for the dispatch code.
36069 
36070   // Shove the dispatch's address into the return slot in the function context.
36071   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
36072   DispatchBB->setIsEHPad(true);
36073 
36074   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
36075   BuildMI(TrapBB, DL, TII->get(X86::TRAP));
36076   DispatchBB->addSuccessor(TrapBB);
36077 
36078   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
36079   DispatchBB->addSuccessor(DispContBB);
36080 
36081   // Insert MBBs.
36082   MF->push_back(DispatchBB);
36083   MF->push_back(DispContBB);
36084   MF->push_back(TrapBB);
36085 
36086   // Insert code into the entry block that creates and registers the function
36087   // context.
36088   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
36089 
36090   // Create the jump table and associated information
36091   unsigned JTE = getJumpTableEncoding();
36092   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
36093   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
36094 
36095   const X86RegisterInfo &RI = TII->getRegisterInfo();
36096   // Add a register mask with no preserved registers.  This results in all
36097   // registers being marked as clobbered.
36098   if (RI.hasBasePointer(*MF)) {
36099     const bool FPIs64Bit =
36100         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
36101     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
36102     MFI->setRestoreBasePointer(MF);
36103 
36104     Register FP = RI.getFrameRegister(*MF);
36105     Register BP = RI.getBaseRegister();
36106     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
36107     addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
36108                  MFI->getRestoreBasePointerOffset())
36109         .addRegMask(RI.getNoPreservedMask());
36110   } else {
36111     BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
36112         .addRegMask(RI.getNoPreservedMask());
36113   }
36114 
36115   // IReg is used as an index in a memory operand and therefore can't be SP
36116   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
36117   addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
36118                     Subtarget.is64Bit() ? 8 : 4);
36119   BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
36120       .addReg(IReg)
36121       .addImm(LPadList.size());
36122   BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
36123 
36124   if (Subtarget.is64Bit()) {
36125     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
36126     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
36127 
36128     // leaq .LJTI0_0(%rip), BReg
36129     BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
36130         .addReg(X86::RIP)
36131         .addImm(1)
36132         .addReg(0)
36133         .addJumpTableIndex(MJTI)
36134         .addReg(0);
36135     // movzx IReg64, IReg
36136     BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
36137         .addImm(0)
36138         .addReg(IReg)
36139         .addImm(X86::sub_32bit);
36140 
36141     switch (JTE) {
36142     case MachineJumpTableInfo::EK_BlockAddress:
36143       // jmpq *(BReg,IReg64,8)
36144       BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
36145           .addReg(BReg)
36146           .addImm(8)
36147           .addReg(IReg64)
36148           .addImm(0)
36149           .addReg(0);
36150       break;
36151     case MachineJumpTableInfo::EK_LabelDifference32: {
36152       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
36153       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
36154       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
36155 
36156       // movl (BReg,IReg64,4), OReg
36157       BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
36158           .addReg(BReg)
36159           .addImm(4)
36160           .addReg(IReg64)
36161           .addImm(0)
36162           .addReg(0);
36163       // movsx OReg64, OReg
36164       BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
36165       // addq BReg, OReg64, TReg
36166       BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
36167           .addReg(OReg64)
36168           .addReg(BReg);
36169       // jmpq *TReg
36170       BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
36171       break;
36172     }
36173     default:
36174       llvm_unreachable("Unexpected jump table encoding");
36175     }
36176   } else {
36177     // jmpl *.LJTI0_0(,IReg,4)
36178     BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
36179         .addReg(0)
36180         .addImm(4)
36181         .addReg(IReg)
36182         .addJumpTableIndex(MJTI)
36183         .addReg(0);
36184   }
36185 
36186   // Add the jump table entries as successors to the MBB.
36187   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
36188   for (auto &LP : LPadList)
36189     if (SeenMBBs.insert(LP).second)
36190       DispContBB->addSuccessor(LP);
36191 
36192   // N.B. the order the invoke BBs are processed in doesn't matter here.
36193   SmallVector<MachineBasicBlock *, 64> MBBLPads;
36194   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
36195   for (MachineBasicBlock *MBB : InvokeBBs) {
36196     // Remove the landing pad successor from the invoke block and replace it
36197     // with the new dispatch block.
36198     // Keep a copy of Successors since it's modified inside the loop.
36199     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
36200                                                    MBB->succ_rend());
36201     // FIXME: Avoid quadratic complexity.
36202     for (auto MBBS : Successors) {
36203       if (MBBS->isEHPad()) {
36204         MBB->removeSuccessor(MBBS);
36205         MBBLPads.push_back(MBBS);
36206       }
36207     }
36208 
36209     MBB->addSuccessor(DispatchBB);
36210 
36211     // Find the invoke call and mark all of the callee-saved registers as
36212     // 'implicit defined' so that they're spilled.  This prevents code from
36213     // moving instructions to before the EH block, where they will never be
36214     // executed.
36215     for (auto &II : reverse(*MBB)) {
36216       if (!II.isCall())
36217         continue;
36218 
36219       DenseMap<unsigned, bool> DefRegs;
36220       for (auto &MOp : II.operands())
36221         if (MOp.isReg())
36222           DefRegs[MOp.getReg()] = true;
36223 
36224       MachineInstrBuilder MIB(*MF, &II);
36225       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
36226         unsigned Reg = SavedRegs[RegIdx];
36227         if (!DefRegs[Reg])
36228           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
36229       }
36230 
36231       break;
36232     }
36233   }
36234 
36235   // Mark all former landing pads as non-landing pads.  The dispatch is the only
36236   // landing pad now.
36237   for (auto &LP : MBBLPads)
36238     LP->setIsEHPad(false);
36239 
36240   // The instruction is gone now.
36241   MI.eraseFromParent();
36242   return BB;
36243 }
36244 
36245 MachineBasicBlock *
36246 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
36247                                                MachineBasicBlock *BB) const {
36248   MachineFunction *MF = BB->getParent();
36249   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36250   const DebugLoc &DL = MI.getDebugLoc();
36251 
36252   auto TMMImmToTMMReg = [](unsigned Imm) {
36253     assert (Imm < 8 && "Illegal tmm index");
36254     return X86::TMM0 + Imm;
36255   };
36256   switch (MI.getOpcode()) {
36257   default: llvm_unreachable("Unexpected instr type to insert");
36258   case X86::TLS_addr32:
36259   case X86::TLS_addr64:
36260   case X86::TLS_addrX32:
36261   case X86::TLS_base_addr32:
36262   case X86::TLS_base_addr64:
36263   case X86::TLS_base_addrX32:
36264     return EmitLoweredTLSAddr(MI, BB);
36265   case X86::INDIRECT_THUNK_CALL32:
36266   case X86::INDIRECT_THUNK_CALL64:
36267   case X86::INDIRECT_THUNK_TCRETURN32:
36268   case X86::INDIRECT_THUNK_TCRETURN64:
36269     return EmitLoweredIndirectThunk(MI, BB);
36270   case X86::CATCHRET:
36271     return EmitLoweredCatchRet(MI, BB);
36272   case X86::SEG_ALLOCA_32:
36273   case X86::SEG_ALLOCA_64:
36274     return EmitLoweredSegAlloca(MI, BB);
36275   case X86::PROBED_ALLOCA_32:
36276   case X86::PROBED_ALLOCA_64:
36277     return EmitLoweredProbedAlloca(MI, BB);
36278   case X86::TLSCall_32:
36279   case X86::TLSCall_64:
36280     return EmitLoweredTLSCall(MI, BB);
36281   case X86::CMOV_FR16:
36282   case X86::CMOV_FR16X:
36283   case X86::CMOV_FR32:
36284   case X86::CMOV_FR32X:
36285   case X86::CMOV_FR64:
36286   case X86::CMOV_FR64X:
36287   case X86::CMOV_GR8:
36288   case X86::CMOV_GR16:
36289   case X86::CMOV_GR32:
36290   case X86::CMOV_RFP32:
36291   case X86::CMOV_RFP64:
36292   case X86::CMOV_RFP80:
36293   case X86::CMOV_VR64:
36294   case X86::CMOV_VR128:
36295   case X86::CMOV_VR128X:
36296   case X86::CMOV_VR256:
36297   case X86::CMOV_VR256X:
36298   case X86::CMOV_VR512:
36299   case X86::CMOV_VK1:
36300   case X86::CMOV_VK2:
36301   case X86::CMOV_VK4:
36302   case X86::CMOV_VK8:
36303   case X86::CMOV_VK16:
36304   case X86::CMOV_VK32:
36305   case X86::CMOV_VK64:
36306     return EmitLoweredSelect(MI, BB);
36307 
36308   case X86::RDFLAGS32:
36309   case X86::RDFLAGS64: {
36310     unsigned PushF =
36311         MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
36312     unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
36313     MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
36314     // Permit reads of the EFLAGS and DF registers without them being defined.
36315     // This intrinsic exists to read external processor state in flags, such as
36316     // the trap flag, interrupt flag, and direction flag, none of which are
36317     // modeled by the backend.
36318     assert(Push->getOperand(2).getReg() == X86::EFLAGS &&
36319            "Unexpected register in operand!");
36320     Push->getOperand(2).setIsUndef();
36321     assert(Push->getOperand(3).getReg() == X86::DF &&
36322            "Unexpected register in operand!");
36323     Push->getOperand(3).setIsUndef();
36324     BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
36325 
36326     MI.eraseFromParent(); // The pseudo is gone now.
36327     return BB;
36328   }
36329 
36330   case X86::WRFLAGS32:
36331   case X86::WRFLAGS64: {
36332     unsigned Push =
36333         MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
36334     unsigned PopF =
36335         MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
36336     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
36337     BuildMI(*BB, MI, DL, TII->get(PopF));
36338 
36339     MI.eraseFromParent(); // The pseudo is gone now.
36340     return BB;
36341   }
36342 
36343   case X86::FP32_TO_INT16_IN_MEM:
36344   case X86::FP32_TO_INT32_IN_MEM:
36345   case X86::FP32_TO_INT64_IN_MEM:
36346   case X86::FP64_TO_INT16_IN_MEM:
36347   case X86::FP64_TO_INT32_IN_MEM:
36348   case X86::FP64_TO_INT64_IN_MEM:
36349   case X86::FP80_TO_INT16_IN_MEM:
36350   case X86::FP80_TO_INT32_IN_MEM:
36351   case X86::FP80_TO_INT64_IN_MEM: {
36352     // Change the floating point control register to use "round towards zero"
36353     // mode when truncating to an integer value.
36354     int OrigCWFrameIdx =
36355         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
36356     addFrameReference(BuildMI(*BB, MI, DL,
36357                               TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
36358 
36359     // Load the old value of the control word...
36360     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
36361     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
36362                       OrigCWFrameIdx);
36363 
36364     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
36365     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
36366     BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
36367       .addReg(OldCW, RegState::Kill).addImm(0xC00);
36368 
36369     // Extract to 16 bits.
36370     Register NewCW16 =
36371         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
36372     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
36373       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
36374 
36375     // Prepare memory for FLDCW.
36376     int NewCWFrameIdx =
36377         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
36378     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
36379                       NewCWFrameIdx)
36380       .addReg(NewCW16, RegState::Kill);
36381 
36382     // Reload the modified control word now...
36383     addFrameReference(BuildMI(*BB, MI, DL,
36384                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
36385 
36386     // Get the X86 opcode to use.
36387     unsigned Opc;
36388     switch (MI.getOpcode()) {
36389     default: llvm_unreachable("illegal opcode!");
36390     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
36391     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
36392     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
36393     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
36394     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
36395     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
36396     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
36397     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
36398     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
36399     }
36400 
36401     X86AddressMode AM = getAddressFromInstr(&MI, 0);
36402     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
36403         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
36404 
36405     // Reload the original control word now.
36406     addFrameReference(BuildMI(*BB, MI, DL,
36407                               TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
36408 
36409     MI.eraseFromParent(); // The pseudo instruction is gone now.
36410     return BB;
36411   }
36412 
36413   // xbegin
36414   case X86::XBEGIN:
36415     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
36416 
36417   case X86::VAARG_64:
36418   case X86::VAARG_X32:
36419     return EmitVAARGWithCustomInserter(MI, BB);
36420 
36421   case X86::EH_SjLj_SetJmp32:
36422   case X86::EH_SjLj_SetJmp64:
36423     return emitEHSjLjSetJmp(MI, BB);
36424 
36425   case X86::EH_SjLj_LongJmp32:
36426   case X86::EH_SjLj_LongJmp64:
36427     return emitEHSjLjLongJmp(MI, BB);
36428 
36429   case X86::Int_eh_sjlj_setup_dispatch:
36430     return EmitSjLjDispatchBlock(MI, BB);
36431 
36432   case TargetOpcode::STATEPOINT:
36433     // As an implementation detail, STATEPOINT shares the STACKMAP format at
36434     // this point in the process.  We diverge later.
36435     return emitPatchPoint(MI, BB);
36436 
36437   case TargetOpcode::STACKMAP:
36438   case TargetOpcode::PATCHPOINT:
36439     return emitPatchPoint(MI, BB);
36440 
36441   case TargetOpcode::PATCHABLE_EVENT_CALL:
36442   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
36443     return BB;
36444 
36445   case X86::LCMPXCHG8B: {
36446     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
36447     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
36448     // requires a memory operand. If it happens that current architecture is
36449     // i686 and for current function we need a base pointer
36450     // - which is ESI for i686 - register allocator would not be able to
36451     // allocate registers for an address in form of X(%reg, %reg, Y)
36452     // - there never would be enough unreserved registers during regalloc
36453     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
36454     // We are giving a hand to register allocator by precomputing the address in
36455     // a new vreg using LEA.
36456 
36457     // If it is not i686 or there is no base pointer - nothing to do here.
36458     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
36459       return BB;
36460 
36461     // Even though this code does not necessarily needs the base pointer to
36462     // be ESI, we check for that. The reason: if this assert fails, there are
36463     // some changes happened in the compiler base pointer handling, which most
36464     // probably have to be addressed somehow here.
36465     assert(TRI->getBaseRegister() == X86::ESI &&
36466            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
36467            "base pointer in mind");
36468 
36469     MachineRegisterInfo &MRI = MF->getRegInfo();
36470     MVT SPTy = getPointerTy(MF->getDataLayout());
36471     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
36472     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
36473 
36474     X86AddressMode AM = getAddressFromInstr(&MI, 0);
36475     // Regalloc does not need any help when the memory operand of CMPXCHG8B
36476     // does not use index register.
36477     if (AM.IndexReg == X86::NoRegister)
36478       return BB;
36479 
36480     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
36481     // four operand definitions that are E[ABCD] registers. We skip them and
36482     // then insert the LEA.
36483     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
36484     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
36485                                    RMBBI->definesRegister(X86::EBX) ||
36486                                    RMBBI->definesRegister(X86::ECX) ||
36487                                    RMBBI->definesRegister(X86::EDX))) {
36488       ++RMBBI;
36489     }
36490     MachineBasicBlock::iterator MBBI(RMBBI);
36491     addFullAddress(
36492         BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
36493 
36494     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
36495 
36496     return BB;
36497   }
36498   case X86::LCMPXCHG16B_NO_RBX: {
36499     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
36500     Register BasePtr = TRI->getBaseRegister();
36501     if (TRI->hasBasePointer(*MF) &&
36502         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
36503       if (!BB->isLiveIn(BasePtr))
36504         BB->addLiveIn(BasePtr);
36505       // Save RBX into a virtual register.
36506       Register SaveRBX =
36507           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36508       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
36509           .addReg(X86::RBX);
36510       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36511       MachineInstrBuilder MIB =
36512           BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
36513       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
36514         MIB.add(MI.getOperand(Idx));
36515       MIB.add(MI.getOperand(X86::AddrNumOperands));
36516       MIB.addReg(SaveRBX);
36517     } else {
36518       // Simple case, just copy the virtual register to RBX.
36519       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::RBX)
36520           .add(MI.getOperand(X86::AddrNumOperands));
36521       MachineInstrBuilder MIB =
36522           BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B));
36523       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
36524         MIB.add(MI.getOperand(Idx));
36525     }
36526     MI.eraseFromParent();
36527     return BB;
36528   }
36529   case X86::MWAITX: {
36530     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
36531     Register BasePtr = TRI->getBaseRegister();
36532     bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
36533     // If no need to save the base pointer, we generate MWAITXrrr,
36534     // else we generate pseudo MWAITX_SAVE_RBX.
36535     if (!IsRBX || !TRI->hasBasePointer(*MF)) {
36536       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
36537           .addReg(MI.getOperand(0).getReg());
36538       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
36539           .addReg(MI.getOperand(1).getReg());
36540       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EBX)
36541           .addReg(MI.getOperand(2).getReg());
36542       BuildMI(*BB, MI, DL, TII->get(X86::MWAITXrrr));
36543       MI.eraseFromParent();
36544     } else {
36545       if (!BB->isLiveIn(BasePtr)) {
36546         BB->addLiveIn(BasePtr);
36547       }
36548       // Parameters can be copied into ECX and EAX but not EBX yet.
36549       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
36550           .addReg(MI.getOperand(0).getReg());
36551       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
36552           .addReg(MI.getOperand(1).getReg());
36553       assert(Subtarget.is64Bit() && "Expected 64-bit mode!");
36554       // Save RBX into a virtual register.
36555       Register SaveRBX =
36556           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36557       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
36558           .addReg(X86::RBX);
36559       // Generate mwaitx pseudo.
36560       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36561       BuildMI(*BB, MI, DL, TII->get(X86::MWAITX_SAVE_RBX))
36562           .addDef(Dst) // Destination tied in with SaveRBX.
36563           .addReg(MI.getOperand(2).getReg()) // input value of EBX.
36564           .addUse(SaveRBX);                  // Save of base pointer.
36565       MI.eraseFromParent();
36566     }
36567     return BB;
36568   }
36569   case TargetOpcode::PREALLOCATED_SETUP: {
36570     assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
36571     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
36572     MFI->setHasPreallocatedCall(true);
36573     int64_t PreallocatedId = MI.getOperand(0).getImm();
36574     size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
36575     assert(StackAdjustment != 0 && "0 stack adjustment");
36576     LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
36577                       << StackAdjustment << "\n");
36578     BuildMI(*BB, MI, DL, TII->get(X86::SUB32ri), X86::ESP)
36579         .addReg(X86::ESP)
36580         .addImm(StackAdjustment);
36581     MI.eraseFromParent();
36582     return BB;
36583   }
36584   case TargetOpcode::PREALLOCATED_ARG: {
36585     assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
36586     int64_t PreallocatedId = MI.getOperand(1).getImm();
36587     int64_t ArgIdx = MI.getOperand(2).getImm();
36588     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
36589     size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
36590     LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
36591                       << ", arg offset " << ArgOffset << "\n");
36592     // stack pointer + offset
36593     addRegOffset(
36594         BuildMI(*BB, MI, DL, TII->get(X86::LEA32r), MI.getOperand(0).getReg()),
36595         X86::ESP, false, ArgOffset);
36596     MI.eraseFromParent();
36597     return BB;
36598   }
36599   case X86::PTDPBSSD:
36600   case X86::PTDPBSUD:
36601   case X86::PTDPBUSD:
36602   case X86::PTDPBUUD:
36603   case X86::PTDPBF16PS: {
36604     unsigned Opc;
36605     switch (MI.getOpcode()) {
36606     default: llvm_unreachable("illegal opcode!");
36607     case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
36608     case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
36609     case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
36610     case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
36611     case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
36612     }
36613 
36614     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
36615     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
36616     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
36617     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
36618     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
36619 
36620     MI.eraseFromParent(); // The pseudo is gone now.
36621     return BB;
36622   }
36623   case X86::PTILEZERO: {
36624     unsigned Imm = MI.getOperand(0).getImm();
36625     BuildMI(*BB, MI, DL, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
36626     MI.eraseFromParent(); // The pseudo is gone now.
36627     return BB;
36628   }
36629   case X86::PTILELOADD:
36630   case X86::PTILELOADDT1:
36631   case X86::PTILESTORED: {
36632     unsigned Opc;
36633     switch (MI.getOpcode()) {
36634     default: llvm_unreachable("illegal opcode!");
36635     case X86::PTILELOADD:   Opc = X86::TILELOADD;   break;
36636     case X86::PTILELOADDT1: Opc = X86::TILELOADDT1; break;
36637     case X86::PTILESTORED:  Opc = X86::TILESTORED;  break;
36638     }
36639 
36640     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
36641     unsigned CurOp = 0;
36642     if (Opc != X86::TILESTORED)
36643       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
36644                  RegState::Define);
36645 
36646     MIB.add(MI.getOperand(CurOp++)); // base
36647     MIB.add(MI.getOperand(CurOp++)); // scale
36648     MIB.add(MI.getOperand(CurOp++)); // index -- stride
36649     MIB.add(MI.getOperand(CurOp++)); // displacement
36650     MIB.add(MI.getOperand(CurOp++)); // segment
36651 
36652     if (Opc == X86::TILESTORED)
36653       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
36654                  RegState::Undef);
36655 
36656     MI.eraseFromParent(); // The pseudo is gone now.
36657     return BB;
36658   }
36659   }
36660 }
36661 
36662 //===----------------------------------------------------------------------===//
36663 //                           X86 Optimization Hooks
36664 //===----------------------------------------------------------------------===//
36665 
36666 bool
36667 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
36668                                                 const APInt &DemandedBits,
36669                                                 const APInt &DemandedElts,
36670                                                 TargetLoweringOpt &TLO) const {
36671   EVT VT = Op.getValueType();
36672   unsigned Opcode = Op.getOpcode();
36673   unsigned EltSize = VT.getScalarSizeInBits();
36674 
36675   if (VT.isVector()) {
36676     // If the constant is only all signbits in the active bits, then we should
36677     // extend it to the entire constant to allow it act as a boolean constant
36678     // vector.
36679     auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
36680       if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
36681         return false;
36682       for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
36683         if (!DemandedElts[i] || V.getOperand(i).isUndef())
36684           continue;
36685         const APInt &Val = V.getConstantOperandAPInt(i);
36686         if (Val.getBitWidth() > Val.getNumSignBits() &&
36687             Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
36688           return true;
36689       }
36690       return false;
36691     };
36692     // For vectors - if we have a constant, then try to sign extend.
36693     // TODO: Handle AND/ANDN cases.
36694     unsigned ActiveBits = DemandedBits.getActiveBits();
36695     if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
36696         (Opcode == ISD::OR || Opcode == ISD::XOR) &&
36697         NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
36698       EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
36699       EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
36700                                     VT.getVectorNumElements());
36701       SDValue NewC =
36702           TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
36703                           Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
36704       SDValue NewOp =
36705           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
36706       return TLO.CombineTo(Op, NewOp);
36707     }
36708     return false;
36709   }
36710 
36711   // Only optimize Ands to prevent shrinking a constant that could be
36712   // matched by movzx.
36713   if (Opcode != ISD::AND)
36714     return false;
36715 
36716   // Make sure the RHS really is a constant.
36717   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
36718   if (!C)
36719     return false;
36720 
36721   const APInt &Mask = C->getAPIntValue();
36722 
36723   // Clear all non-demanded bits initially.
36724   APInt ShrunkMask = Mask & DemandedBits;
36725 
36726   // Find the width of the shrunk mask.
36727   unsigned Width = ShrunkMask.getActiveBits();
36728 
36729   // If the mask is all 0s there's nothing to do here.
36730   if (Width == 0)
36731     return false;
36732 
36733   // Find the next power of 2 width, rounding up to a byte.
36734   Width = PowerOf2Ceil(std::max(Width, 8U));
36735   // Truncate the width to size to handle illegal types.
36736   Width = std::min(Width, EltSize);
36737 
36738   // Calculate a possible zero extend mask for this constant.
36739   APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
36740 
36741   // If we aren't changing the mask, just return true to keep it and prevent
36742   // the caller from optimizing.
36743   if (ZeroExtendMask == Mask)
36744     return true;
36745 
36746   // Make sure the new mask can be represented by a combination of mask bits
36747   // and non-demanded bits.
36748   if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
36749     return false;
36750 
36751   // Replace the constant with the zero extend mask.
36752   SDLoc DL(Op);
36753   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
36754   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
36755   return TLO.CombineTo(Op, NewOp);
36756 }
36757 
36758 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
36759                                                       KnownBits &Known,
36760                                                       const APInt &DemandedElts,
36761                                                       const SelectionDAG &DAG,
36762                                                       unsigned Depth) const {
36763   unsigned BitWidth = Known.getBitWidth();
36764   unsigned NumElts = DemandedElts.getBitWidth();
36765   unsigned Opc = Op.getOpcode();
36766   EVT VT = Op.getValueType();
36767   assert((Opc >= ISD::BUILTIN_OP_END ||
36768           Opc == ISD::INTRINSIC_WO_CHAIN ||
36769           Opc == ISD::INTRINSIC_W_CHAIN ||
36770           Opc == ISD::INTRINSIC_VOID) &&
36771          "Should use MaskedValueIsZero if you don't know whether Op"
36772          " is a target node!");
36773 
36774   Known.resetAll();
36775   switch (Opc) {
36776   default: break;
36777   case X86ISD::SETCC:
36778     Known.Zero.setBitsFrom(1);
36779     break;
36780   case X86ISD::MOVMSK: {
36781     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
36782     Known.Zero.setBitsFrom(NumLoBits);
36783     break;
36784   }
36785   case X86ISD::PEXTRB:
36786   case X86ISD::PEXTRW: {
36787     SDValue Src = Op.getOperand(0);
36788     EVT SrcVT = Src.getValueType();
36789     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
36790                                             Op.getConstantOperandVal(1));
36791     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
36792     Known = Known.anyextOrTrunc(BitWidth);
36793     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
36794     break;
36795   }
36796   case X86ISD::VSRAI:
36797   case X86ISD::VSHLI:
36798   case X86ISD::VSRLI: {
36799     unsigned ShAmt = Op.getConstantOperandVal(1);
36800     if (ShAmt >= VT.getScalarSizeInBits()) {
36801       Known.setAllZero();
36802       break;
36803     }
36804 
36805     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36806     if (Opc == X86ISD::VSHLI) {
36807       Known.Zero <<= ShAmt;
36808       Known.One <<= ShAmt;
36809       // Low bits are known zero.
36810       Known.Zero.setLowBits(ShAmt);
36811     } else if (Opc == X86ISD::VSRLI) {
36812       Known.Zero.lshrInPlace(ShAmt);
36813       Known.One.lshrInPlace(ShAmt);
36814       // High bits are known zero.
36815       Known.Zero.setHighBits(ShAmt);
36816     } else {
36817       Known.Zero.ashrInPlace(ShAmt);
36818       Known.One.ashrInPlace(ShAmt);
36819     }
36820     break;
36821   }
36822   case X86ISD::PACKUS: {
36823     // PACKUS is just a truncation if the upper half is zero.
36824     APInt DemandedLHS, DemandedRHS;
36825     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
36826 
36827     Known.One = APInt::getAllOnes(BitWidth * 2);
36828     Known.Zero = APInt::getAllOnes(BitWidth * 2);
36829 
36830     KnownBits Known2;
36831     if (!!DemandedLHS) {
36832       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
36833       Known = KnownBits::commonBits(Known, Known2);
36834     }
36835     if (!!DemandedRHS) {
36836       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
36837       Known = KnownBits::commonBits(Known, Known2);
36838     }
36839 
36840     if (Known.countMinLeadingZeros() < BitWidth)
36841       Known.resetAll();
36842     Known = Known.trunc(BitWidth);
36843     break;
36844   }
36845   case X86ISD::VBROADCAST: {
36846     SDValue Src = Op.getOperand(0);
36847     if (!Src.getSimpleValueType().isVector()) {
36848       Known = DAG.computeKnownBits(Src, Depth + 1);
36849       return;
36850     }
36851     break;
36852   }
36853   case X86ISD::AND: {
36854     if (Op.getResNo() == 0) {
36855       KnownBits Known2;
36856       Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36857       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36858       Known &= Known2;
36859     }
36860     break;
36861   }
36862   case X86ISD::ANDNP: {
36863     KnownBits Known2;
36864     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36865     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36866 
36867     // ANDNP = (~X & Y);
36868     Known.One &= Known2.Zero;
36869     Known.Zero |= Known2.One;
36870     break;
36871   }
36872   case X86ISD::FOR: {
36873     KnownBits Known2;
36874     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36875     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36876 
36877     Known |= Known2;
36878     break;
36879   }
36880   case X86ISD::PSADBW: {
36881     assert(VT.getScalarType() == MVT::i64 &&
36882            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
36883            "Unexpected PSADBW types");
36884 
36885     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
36886     Known.Zero.setBitsFrom(16);
36887     break;
36888   }
36889   case X86ISD::PMULUDQ: {
36890     KnownBits Known2;
36891     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36892     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36893 
36894     Known = Known.trunc(BitWidth / 2).zext(BitWidth);
36895     Known2 = Known2.trunc(BitWidth / 2).zext(BitWidth);
36896     Known = KnownBits::mul(Known, Known2);
36897     break;
36898   }
36899   case X86ISD::CMOV: {
36900     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
36901     // If we don't know any bits, early out.
36902     if (Known.isUnknown())
36903       break;
36904     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
36905 
36906     // Only known if known in both the LHS and RHS.
36907     Known = KnownBits::commonBits(Known, Known2);
36908     break;
36909   }
36910   case X86ISD::BEXTR:
36911   case X86ISD::BEXTRI: {
36912     SDValue Op0 = Op.getOperand(0);
36913     SDValue Op1 = Op.getOperand(1);
36914 
36915     if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
36916       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
36917       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
36918 
36919       // If the length is 0, the result is 0.
36920       if (Length == 0) {
36921         Known.setAllZero();
36922         break;
36923       }
36924 
36925       if ((Shift + Length) <= BitWidth) {
36926         Known = DAG.computeKnownBits(Op0, Depth + 1);
36927         Known = Known.extractBits(Length, Shift);
36928         Known = Known.zextOrTrunc(BitWidth);
36929       }
36930     }
36931     break;
36932   }
36933   case X86ISD::PDEP: {
36934     KnownBits Known2;
36935     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36936     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36937     // Zeros are retained from the mask operand. But not ones.
36938     Known.One.clearAllBits();
36939     // The result will have at least as many trailing zeros as the non-mask
36940     // operand since bits can only map to the same or higher bit position.
36941     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
36942     break;
36943   }
36944   case X86ISD::PEXT: {
36945     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36946     // The result has as many leading zeros as the number of zeroes in the mask.
36947     unsigned Count = Known.Zero.countPopulation();
36948     Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
36949     Known.One.clearAllBits();
36950     break;
36951   }
36952   case X86ISD::VTRUNC:
36953   case X86ISD::VTRUNCS:
36954   case X86ISD::VTRUNCUS:
36955   case X86ISD::CVTSI2P:
36956   case X86ISD::CVTUI2P:
36957   case X86ISD::CVTP2SI:
36958   case X86ISD::CVTP2UI:
36959   case X86ISD::MCVTP2SI:
36960   case X86ISD::MCVTP2UI:
36961   case X86ISD::CVTTP2SI:
36962   case X86ISD::CVTTP2UI:
36963   case X86ISD::MCVTTP2SI:
36964   case X86ISD::MCVTTP2UI:
36965   case X86ISD::MCVTSI2P:
36966   case X86ISD::MCVTUI2P:
36967   case X86ISD::VFPROUND:
36968   case X86ISD::VMFPROUND:
36969   case X86ISD::CVTPS2PH:
36970   case X86ISD::MCVTPS2PH: {
36971     // Truncations/Conversions - upper elements are known zero.
36972     EVT SrcVT = Op.getOperand(0).getValueType();
36973     if (SrcVT.isVector()) {
36974       unsigned NumSrcElts = SrcVT.getVectorNumElements();
36975       if (NumElts > NumSrcElts &&
36976           DemandedElts.countTrailingZeros() >= NumSrcElts)
36977         Known.setAllZero();
36978     }
36979     break;
36980   }
36981   case X86ISD::STRICT_CVTTP2SI:
36982   case X86ISD::STRICT_CVTTP2UI:
36983   case X86ISD::STRICT_CVTSI2P:
36984   case X86ISD::STRICT_CVTUI2P:
36985   case X86ISD::STRICT_VFPROUND:
36986   case X86ISD::STRICT_CVTPS2PH: {
36987     // Strict Conversions - upper elements are known zero.
36988     EVT SrcVT = Op.getOperand(1).getValueType();
36989     if (SrcVT.isVector()) {
36990       unsigned NumSrcElts = SrcVT.getVectorNumElements();
36991       if (NumElts > NumSrcElts &&
36992           DemandedElts.countTrailingZeros() >= NumSrcElts)
36993         Known.setAllZero();
36994     }
36995     break;
36996   }
36997   case X86ISD::MOVQ2DQ: {
36998     // Move from MMX to XMM. Upper half of XMM should be 0.
36999     if (DemandedElts.countTrailingZeros() >= (NumElts / 2))
37000       Known.setAllZero();
37001     break;
37002   }
37003   case X86ISD::VBROADCAST_LOAD: {
37004     APInt UndefElts;
37005     SmallVector<APInt, 16> EltBits;
37006     if (getTargetConstantBitsFromNode(Op, BitWidth, UndefElts, EltBits,
37007                                       /*AllowWholeUndefs*/ false,
37008                                       /*AllowPartialUndefs*/ false)) {
37009       Known.Zero.setAllBits();
37010       Known.One.setAllBits();
37011       for (unsigned I = 0; I != NumElts; ++I) {
37012         if (!DemandedElts[I])
37013           continue;
37014         if (UndefElts[I]) {
37015           Known.resetAll();
37016           break;
37017         }
37018         KnownBits Known2 = KnownBits::makeConstant(EltBits[I]);
37019         Known = KnownBits::commonBits(Known, Known2);
37020       }
37021       return;
37022     }
37023     break;
37024   }
37025   }
37026 
37027   // Handle target shuffles.
37028   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
37029   if (isTargetShuffle(Opc)) {
37030     SmallVector<int, 64> Mask;
37031     SmallVector<SDValue, 2> Ops;
37032     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
37033       unsigned NumOps = Ops.size();
37034       unsigned NumElts = VT.getVectorNumElements();
37035       if (Mask.size() == NumElts) {
37036         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
37037         Known.Zero.setAllBits(); Known.One.setAllBits();
37038         for (unsigned i = 0; i != NumElts; ++i) {
37039           if (!DemandedElts[i])
37040             continue;
37041           int M = Mask[i];
37042           if (M == SM_SentinelUndef) {
37043             // For UNDEF elements, we don't know anything about the common state
37044             // of the shuffle result.
37045             Known.resetAll();
37046             break;
37047           }
37048           if (M == SM_SentinelZero) {
37049             Known.One.clearAllBits();
37050             continue;
37051           }
37052           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
37053                  "Shuffle index out of range");
37054 
37055           unsigned OpIdx = (unsigned)M / NumElts;
37056           unsigned EltIdx = (unsigned)M % NumElts;
37057           if (Ops[OpIdx].getValueType() != VT) {
37058             // TODO - handle target shuffle ops with different value types.
37059             Known.resetAll();
37060             break;
37061           }
37062           DemandedOps[OpIdx].setBit(EltIdx);
37063         }
37064         // Known bits are the values that are shared by every demanded element.
37065         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
37066           if (!DemandedOps[i])
37067             continue;
37068           KnownBits Known2 =
37069               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
37070           Known = KnownBits::commonBits(Known, Known2);
37071         }
37072       }
37073     }
37074   }
37075 }
37076 
37077 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
37078     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
37079     unsigned Depth) const {
37080   EVT VT = Op.getValueType();
37081   unsigned VTBits = VT.getScalarSizeInBits();
37082   unsigned Opcode = Op.getOpcode();
37083   switch (Opcode) {
37084   case X86ISD::SETCC_CARRY:
37085     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
37086     return VTBits;
37087 
37088   case X86ISD::VTRUNC: {
37089     SDValue Src = Op.getOperand(0);
37090     MVT SrcVT = Src.getSimpleValueType();
37091     unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
37092     assert(VTBits < NumSrcBits && "Illegal truncation input type");
37093     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
37094     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
37095     if (Tmp > (NumSrcBits - VTBits))
37096       return Tmp - (NumSrcBits - VTBits);
37097     return 1;
37098   }
37099 
37100   case X86ISD::PACKSS: {
37101     // PACKSS is just a truncation if the sign bits extend to the packed size.
37102     APInt DemandedLHS, DemandedRHS;
37103     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
37104                         DemandedRHS);
37105 
37106     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
37107     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
37108     if (!!DemandedLHS)
37109       Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
37110     if (!!DemandedRHS)
37111       Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
37112     unsigned Tmp = std::min(Tmp0, Tmp1);
37113     if (Tmp > (SrcBits - VTBits))
37114       return Tmp - (SrcBits - VTBits);
37115     return 1;
37116   }
37117 
37118   case X86ISD::VBROADCAST: {
37119     SDValue Src = Op.getOperand(0);
37120     if (!Src.getSimpleValueType().isVector())
37121       return DAG.ComputeNumSignBits(Src, Depth + 1);
37122     break;
37123   }
37124 
37125   case X86ISD::VSHLI: {
37126     SDValue Src = Op.getOperand(0);
37127     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
37128     if (ShiftVal.uge(VTBits))
37129       return VTBits; // Shifted all bits out --> zero.
37130     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
37131     if (ShiftVal.uge(Tmp))
37132       return 1; // Shifted all sign bits out --> unknown.
37133     return Tmp - ShiftVal.getZExtValue();
37134   }
37135 
37136   case X86ISD::VSRAI: {
37137     SDValue Src = Op.getOperand(0);
37138     APInt ShiftVal = Op.getConstantOperandAPInt(1);
37139     if (ShiftVal.uge(VTBits - 1))
37140       return VTBits; // Sign splat.
37141     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
37142     ShiftVal += Tmp;
37143     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
37144   }
37145 
37146   case X86ISD::FSETCC:
37147     // cmpss/cmpsd return zero/all-bits result values in the bottom element.
37148     if (VT == MVT::f32 || VT == MVT::f64 ||
37149         ((VT == MVT::v4f32 || VT == MVT::v2f64) && DemandedElts == 1))
37150       return VTBits;
37151     break;
37152 
37153   case X86ISD::PCMPGT:
37154   case X86ISD::PCMPEQ:
37155   case X86ISD::CMPP:
37156   case X86ISD::VPCOM:
37157   case X86ISD::VPCOMU:
37158     // Vector compares return zero/all-bits result values.
37159     return VTBits;
37160 
37161   case X86ISD::ANDNP: {
37162     unsigned Tmp0 =
37163         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
37164     if (Tmp0 == 1) return 1; // Early out.
37165     unsigned Tmp1 =
37166         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
37167     return std::min(Tmp0, Tmp1);
37168   }
37169 
37170   case X86ISD::CMOV: {
37171     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
37172     if (Tmp0 == 1) return 1;  // Early out.
37173     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
37174     return std::min(Tmp0, Tmp1);
37175   }
37176   }
37177 
37178   // Handle target shuffles.
37179   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
37180   if (isTargetShuffle(Opcode)) {
37181     SmallVector<int, 64> Mask;
37182     SmallVector<SDValue, 2> Ops;
37183     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
37184       unsigned NumOps = Ops.size();
37185       unsigned NumElts = VT.getVectorNumElements();
37186       if (Mask.size() == NumElts) {
37187         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
37188         for (unsigned i = 0; i != NumElts; ++i) {
37189           if (!DemandedElts[i])
37190             continue;
37191           int M = Mask[i];
37192           if (M == SM_SentinelUndef) {
37193             // For UNDEF elements, we don't know anything about the common state
37194             // of the shuffle result.
37195             return 1;
37196           } else if (M == SM_SentinelZero) {
37197             // Zero = all sign bits.
37198             continue;
37199           }
37200           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
37201                  "Shuffle index out of range");
37202 
37203           unsigned OpIdx = (unsigned)M / NumElts;
37204           unsigned EltIdx = (unsigned)M % NumElts;
37205           if (Ops[OpIdx].getValueType() != VT) {
37206             // TODO - handle target shuffle ops with different value types.
37207             return 1;
37208           }
37209           DemandedOps[OpIdx].setBit(EltIdx);
37210         }
37211         unsigned Tmp0 = VTBits;
37212         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
37213           if (!DemandedOps[i])
37214             continue;
37215           unsigned Tmp1 =
37216               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
37217           Tmp0 = std::min(Tmp0, Tmp1);
37218         }
37219         return Tmp0;
37220       }
37221     }
37222   }
37223 
37224   // Fallback case.
37225   return 1;
37226 }
37227 
37228 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
37229   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
37230     return N->getOperand(0);
37231   return N;
37232 }
37233 
37234 // Helper to look for a normal load that can be narrowed into a vzload with the
37235 // specified VT and memory VT. Returns SDValue() on failure.
37236 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
37237                                   SelectionDAG &DAG) {
37238   // Can't if the load is volatile or atomic.
37239   if (!LN->isSimple())
37240     return SDValue();
37241 
37242   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37243   SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
37244   return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
37245                                  LN->getPointerInfo(), LN->getOriginalAlign(),
37246                                  LN->getMemOperand()->getFlags());
37247 }
37248 
37249 // Attempt to match a combined shuffle mask against supported unary shuffle
37250 // instructions.
37251 // TODO: Investigate sharing more of this with shuffle lowering.
37252 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
37253                               bool AllowFloatDomain, bool AllowIntDomain,
37254                               SDValue V1, const SelectionDAG &DAG,
37255                               const X86Subtarget &Subtarget, unsigned &Shuffle,
37256                               MVT &SrcVT, MVT &DstVT) {
37257   unsigned NumMaskElts = Mask.size();
37258   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
37259 
37260   // Match against a VZEXT_MOVL vXi32 and vXi16 zero-extending instruction.
37261   if (Mask[0] == 0 &&
37262       (MaskEltSize == 32 || (MaskEltSize == 16 && Subtarget.hasFP16()))) {
37263     if ((isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) ||
37264         (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37265          isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1))) {
37266       Shuffle = X86ISD::VZEXT_MOVL;
37267       if (MaskEltSize == 16)
37268         SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
37269       else
37270         SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
37271       return true;
37272     }
37273   }
37274 
37275   // Match against a ANY/ZERO_EXTEND_VECTOR_INREG instruction.
37276   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
37277   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
37278                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
37279     unsigned MaxScale = 64 / MaskEltSize;
37280     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
37281       bool MatchAny = true;
37282       bool MatchZero = true;
37283       unsigned NumDstElts = NumMaskElts / Scale;
37284       for (unsigned i = 0; i != NumDstElts && (MatchAny || MatchZero); ++i) {
37285         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
37286           MatchAny = MatchZero = false;
37287           break;
37288         }
37289         MatchAny &= isUndefInRange(Mask, (i * Scale) + 1, Scale - 1);
37290         MatchZero &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
37291       }
37292       if (MatchAny || MatchZero) {
37293         assert(MatchZero && "Failed to match zext but matched aext?");
37294         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
37295         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
37296                                             MVT::getIntegerVT(MaskEltSize);
37297         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
37298 
37299         Shuffle = unsigned(MatchAny ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND);
37300         if (SrcVT.getVectorNumElements() != NumDstElts)
37301           Shuffle = getOpcode_EXTEND_VECTOR_INREG(Shuffle);
37302 
37303         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
37304         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
37305         return true;
37306       }
37307     }
37308   }
37309 
37310   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
37311   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2()) ||
37312        (MaskEltSize == 16 && Subtarget.hasFP16())) &&
37313       isUndefOrEqual(Mask[0], 0) &&
37314       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
37315     Shuffle = X86ISD::VZEXT_MOVL;
37316     if (MaskEltSize == 16)
37317       SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
37318     else
37319       SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
37320     return true;
37321   }
37322 
37323   // Check if we have SSE3 which will let us use MOVDDUP etc. The
37324   // instructions are no slower than UNPCKLPD but has the option to
37325   // fold the input operand into even an unaligned memory load.
37326   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
37327     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG, V1)) {
37328       Shuffle = X86ISD::MOVDDUP;
37329       SrcVT = DstVT = MVT::v2f64;
37330       return true;
37331     }
37332     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
37333       Shuffle = X86ISD::MOVSLDUP;
37334       SrcVT = DstVT = MVT::v4f32;
37335       return true;
37336     }
37337     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, DAG, V1)) {
37338       Shuffle = X86ISD::MOVSHDUP;
37339       SrcVT = DstVT = MVT::v4f32;
37340       return true;
37341     }
37342   }
37343 
37344   if (MaskVT.is256BitVector() && AllowFloatDomain) {
37345     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
37346     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
37347       Shuffle = X86ISD::MOVDDUP;
37348       SrcVT = DstVT = MVT::v4f64;
37349       return true;
37350     }
37351     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
37352                                   V1)) {
37353       Shuffle = X86ISD::MOVSLDUP;
37354       SrcVT = DstVT = MVT::v8f32;
37355       return true;
37356     }
37357     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, DAG,
37358                                   V1)) {
37359       Shuffle = X86ISD::MOVSHDUP;
37360       SrcVT = DstVT = MVT::v8f32;
37361       return true;
37362     }
37363   }
37364 
37365   if (MaskVT.is512BitVector() && AllowFloatDomain) {
37366     assert(Subtarget.hasAVX512() &&
37367            "AVX512 required for 512-bit vector shuffles");
37368     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
37369                                   V1)) {
37370       Shuffle = X86ISD::MOVDDUP;
37371       SrcVT = DstVT = MVT::v8f64;
37372       return true;
37373     }
37374     if (isTargetShuffleEquivalent(
37375             MaskVT, Mask,
37376             {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, DAG, V1)) {
37377       Shuffle = X86ISD::MOVSLDUP;
37378       SrcVT = DstVT = MVT::v16f32;
37379       return true;
37380     }
37381     if (isTargetShuffleEquivalent(
37382             MaskVT, Mask,
37383             {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, DAG, V1)) {
37384       Shuffle = X86ISD::MOVSHDUP;
37385       SrcVT = DstVT = MVT::v16f32;
37386       return true;
37387     }
37388   }
37389 
37390   return false;
37391 }
37392 
37393 // Attempt to match a combined shuffle mask against supported unary immediate
37394 // permute instructions.
37395 // TODO: Investigate sharing more of this with shuffle lowering.
37396 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
37397                                      const APInt &Zeroable,
37398                                      bool AllowFloatDomain, bool AllowIntDomain,
37399                                      const SelectionDAG &DAG,
37400                                      const X86Subtarget &Subtarget,
37401                                      unsigned &Shuffle, MVT &ShuffleVT,
37402                                      unsigned &PermuteImm) {
37403   unsigned NumMaskElts = Mask.size();
37404   unsigned InputSizeInBits = MaskVT.getSizeInBits();
37405   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
37406   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
37407   bool ContainsZeros = isAnyZero(Mask);
37408 
37409   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
37410   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
37411     // Check for lane crossing permutes.
37412     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
37413       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
37414       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
37415         Shuffle = X86ISD::VPERMI;
37416         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
37417         PermuteImm = getV4X86ShuffleImm(Mask);
37418         return true;
37419       }
37420       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
37421         SmallVector<int, 4> RepeatedMask;
37422         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
37423           Shuffle = X86ISD::VPERMI;
37424           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
37425           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
37426           return true;
37427         }
37428       }
37429     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
37430       // VPERMILPD can permute with a non-repeating shuffle.
37431       Shuffle = X86ISD::VPERMILPI;
37432       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
37433       PermuteImm = 0;
37434       for (int i = 0, e = Mask.size(); i != e; ++i) {
37435         int M = Mask[i];
37436         if (M == SM_SentinelUndef)
37437           continue;
37438         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
37439         PermuteImm |= (M & 1) << i;
37440       }
37441       return true;
37442     }
37443   }
37444 
37445   // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
37446   // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
37447   // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
37448   if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
37449       !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
37450     SmallVector<int, 4> RepeatedMask;
37451     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
37452       // Narrow the repeated mask to create 32-bit element permutes.
37453       SmallVector<int, 4> WordMask = RepeatedMask;
37454       if (MaskScalarSizeInBits == 64)
37455         narrowShuffleMaskElts(2, RepeatedMask, WordMask);
37456 
37457       Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
37458       ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
37459       ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
37460       PermuteImm = getV4X86ShuffleImm(WordMask);
37461       return true;
37462     }
37463   }
37464 
37465   // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
37466   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
37467       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37468        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37469        (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
37470     SmallVector<int, 4> RepeatedMask;
37471     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
37472       ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
37473       ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
37474 
37475       // PSHUFLW: permute lower 4 elements only.
37476       if (isUndefOrInRange(LoMask, 0, 4) &&
37477           isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
37478         Shuffle = X86ISD::PSHUFLW;
37479         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
37480         PermuteImm = getV4X86ShuffleImm(LoMask);
37481         return true;
37482       }
37483 
37484       // PSHUFHW: permute upper 4 elements only.
37485       if (isUndefOrInRange(HiMask, 4, 8) &&
37486           isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
37487         // Offset the HiMask so that we can create the shuffle immediate.
37488         int OffsetHiMask[4];
37489         for (int i = 0; i != 4; ++i)
37490           OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
37491 
37492         Shuffle = X86ISD::PSHUFHW;
37493         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
37494         PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
37495         return true;
37496       }
37497     }
37498   }
37499 
37500   // Attempt to match against byte/bit shifts.
37501   if (AllowIntDomain &&
37502       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37503        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37504        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37505     int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
37506                                        Mask, 0, Zeroable, Subtarget);
37507     if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
37508                          32 <= ShuffleVT.getScalarSizeInBits())) {
37509       PermuteImm = (unsigned)ShiftAmt;
37510       return true;
37511     }
37512   }
37513 
37514   // Attempt to match against bit rotates.
37515   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
37516       ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
37517        Subtarget.hasAVX512())) {
37518     int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
37519                                             Subtarget, Mask);
37520     if (0 < RotateAmt) {
37521       Shuffle = X86ISD::VROTLI;
37522       PermuteImm = (unsigned)RotateAmt;
37523       return true;
37524     }
37525   }
37526 
37527   return false;
37528 }
37529 
37530 // Attempt to match a combined unary shuffle mask against supported binary
37531 // shuffle instructions.
37532 // TODO: Investigate sharing more of this with shuffle lowering.
37533 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
37534                                bool AllowFloatDomain, bool AllowIntDomain,
37535                                SDValue &V1, SDValue &V2, const SDLoc &DL,
37536                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
37537                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
37538                                bool IsUnary) {
37539   unsigned NumMaskElts = Mask.size();
37540   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
37541   unsigned SizeInBits = MaskVT.getSizeInBits();
37542 
37543   if (MaskVT.is128BitVector()) {
37544     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG) &&
37545         AllowFloatDomain) {
37546       V2 = V1;
37547       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
37548       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
37549       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
37550       return true;
37551     }
37552     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}, DAG) &&
37553         AllowFloatDomain) {
37554       V2 = V1;
37555       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
37556       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
37557       return true;
37558     }
37559     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}, DAG) &&
37560         Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
37561       std::swap(V1, V2);
37562       Shuffle = X86ISD::MOVSD;
37563       SrcVT = DstVT = MVT::v2f64;
37564       return true;
37565     }
37566     if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG) &&
37567         (AllowFloatDomain || !Subtarget.hasSSE41())) {
37568       Shuffle = X86ISD::MOVSS;
37569       SrcVT = DstVT = MVT::v4f32;
37570       return true;
37571     }
37572     if (isTargetShuffleEquivalent(MaskVT, Mask, {8, 1, 2, 3, 4, 5, 6, 7},
37573                                   DAG) &&
37574         Subtarget.hasFP16()) {
37575       Shuffle = X86ISD::MOVSH;
37576       SrcVT = DstVT = MVT::v8f16;
37577       return true;
37578     }
37579   }
37580 
37581   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
37582   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
37583       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
37584       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
37585     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
37586                              Subtarget)) {
37587       DstVT = MaskVT;
37588       return true;
37589     }
37590   }
37591 
37592   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
37593   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
37594       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37595       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
37596       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37597       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
37598     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
37599                               Subtarget)) {
37600       SrcVT = DstVT = MaskVT;
37601       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
37602         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
37603       return true;
37604     }
37605   }
37606 
37607   // Attempt to match against a OR if we're performing a blend shuffle and the
37608   // non-blended source element is zero in each case.
37609   // TODO: Handle cases where V1/V2 sizes doesn't match SizeInBits.
37610   if (SizeInBits == V1.getValueSizeInBits() &&
37611       SizeInBits == V2.getValueSizeInBits() &&
37612       (EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
37613       (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
37614     bool IsBlend = true;
37615     unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
37616     unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
37617     unsigned Scale1 = NumV1Elts / NumMaskElts;
37618     unsigned Scale2 = NumV2Elts / NumMaskElts;
37619     APInt DemandedZeroV1 = APInt::getZero(NumV1Elts);
37620     APInt DemandedZeroV2 = APInt::getZero(NumV2Elts);
37621     for (unsigned i = 0; i != NumMaskElts; ++i) {
37622       int M = Mask[i];
37623       if (M == SM_SentinelUndef)
37624         continue;
37625       if (M == SM_SentinelZero) {
37626         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
37627         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
37628         continue;
37629       }
37630       if (M == (int)i) {
37631         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
37632         continue;
37633       }
37634       if (M == (int)(i + NumMaskElts)) {
37635         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
37636         continue;
37637       }
37638       IsBlend = false;
37639       break;
37640     }
37641     if (IsBlend) {
37642       if (DAG.MaskedVectorIsZero(V1, DemandedZeroV1) &&
37643           DAG.MaskedVectorIsZero(V2, DemandedZeroV2)) {
37644         Shuffle = ISD::OR;
37645         SrcVT = DstVT = MaskVT.changeTypeToInteger();
37646         return true;
37647       }
37648       if (NumV1Elts == NumV2Elts && NumV1Elts == NumMaskElts) {
37649         // FIXME: handle mismatched sizes?
37650         // TODO: investigate if `ISD::OR` handling in
37651         // `TargetLowering::SimplifyDemandedVectorElts` can be improved instead.
37652         auto computeKnownBitsElementWise = [&DAG](SDValue V) {
37653           unsigned NumElts = V.getValueType().getVectorNumElements();
37654           KnownBits Known(NumElts);
37655           for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
37656             APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
37657             KnownBits PeepholeKnown = DAG.computeKnownBits(V, Mask);
37658             if (PeepholeKnown.isZero())
37659               Known.Zero.setBit(EltIdx);
37660             if (PeepholeKnown.isAllOnes())
37661               Known.One.setBit(EltIdx);
37662           }
37663           return Known;
37664         };
37665 
37666         KnownBits V1Known = computeKnownBitsElementWise(V1);
37667         KnownBits V2Known = computeKnownBitsElementWise(V2);
37668 
37669         for (unsigned i = 0; i != NumMaskElts && IsBlend; ++i) {
37670           int M = Mask[i];
37671           if (M == SM_SentinelUndef)
37672             continue;
37673           if (M == SM_SentinelZero) {
37674             IsBlend &= V1Known.Zero[i] && V2Known.Zero[i];
37675             continue;
37676           }
37677           if (M == (int)i) {
37678             IsBlend &= V2Known.Zero[i] || V1Known.One[i];
37679             continue;
37680           }
37681           if (M == (int)(i + NumMaskElts)) {
37682             IsBlend &= V1Known.Zero[i] || V2Known.One[i];
37683             continue;
37684           }
37685           llvm_unreachable("will not get here.");
37686         }
37687         if (IsBlend) {
37688           Shuffle = ISD::OR;
37689           SrcVT = DstVT = MaskVT.changeTypeToInteger();
37690           return true;
37691         }
37692       }
37693     }
37694   }
37695 
37696   return false;
37697 }
37698 
37699 static bool matchBinaryPermuteShuffle(
37700     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
37701     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
37702     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
37703     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
37704   unsigned NumMaskElts = Mask.size();
37705   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
37706 
37707   // Attempt to match against VALIGND/VALIGNQ rotate.
37708   if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
37709       ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
37710        (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
37711        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37712     if (!isAnyZero(Mask)) {
37713       int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
37714       if (0 < Rotation) {
37715         Shuffle = X86ISD::VALIGN;
37716         if (EltSizeInBits == 64)
37717           ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
37718         else
37719           ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
37720         PermuteImm = Rotation;
37721         return true;
37722       }
37723     }
37724   }
37725 
37726   // Attempt to match against PALIGNR byte rotate.
37727   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
37728                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37729                          (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
37730     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
37731     if (0 < ByteRotation) {
37732       Shuffle = X86ISD::PALIGNR;
37733       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
37734       PermuteImm = ByteRotation;
37735       return true;
37736     }
37737   }
37738 
37739   // Attempt to combine to X86ISD::BLENDI.
37740   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
37741                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
37742       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
37743     uint64_t BlendMask = 0;
37744     bool ForceV1Zero = false, ForceV2Zero = false;
37745     SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
37746     if (matchShuffleAsBlend(V1, V2, TargetMask, Zeroable, ForceV1Zero,
37747                             ForceV2Zero, BlendMask)) {
37748       if (MaskVT == MVT::v16i16) {
37749         // We can only use v16i16 PBLENDW if the lanes are repeated.
37750         SmallVector<int, 8> RepeatedMask;
37751         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
37752                                         RepeatedMask)) {
37753           assert(RepeatedMask.size() == 8 &&
37754                  "Repeated mask size doesn't match!");
37755           PermuteImm = 0;
37756           for (int i = 0; i < 8; ++i)
37757             if (RepeatedMask[i] >= 8)
37758               PermuteImm |= 1 << i;
37759           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
37760           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
37761           Shuffle = X86ISD::BLENDI;
37762           ShuffleVT = MaskVT;
37763           return true;
37764         }
37765       } else {
37766         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
37767         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
37768         PermuteImm = (unsigned)BlendMask;
37769         Shuffle = X86ISD::BLENDI;
37770         ShuffleVT = MaskVT;
37771         return true;
37772       }
37773     }
37774   }
37775 
37776   // Attempt to combine to INSERTPS, but only if it has elements that need to
37777   // be set to zero.
37778   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
37779       MaskVT.is128BitVector() && isAnyZero(Mask) &&
37780       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
37781     Shuffle = X86ISD::INSERTPS;
37782     ShuffleVT = MVT::v4f32;
37783     return true;
37784   }
37785 
37786   // Attempt to combine to SHUFPD.
37787   if (AllowFloatDomain && EltSizeInBits == 64 &&
37788       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37789        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
37790        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37791     bool ForceV1Zero = false, ForceV2Zero = false;
37792     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
37793                                PermuteImm, Mask, Zeroable)) {
37794       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
37795       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
37796       Shuffle = X86ISD::SHUFP;
37797       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
37798       return true;
37799     }
37800   }
37801 
37802   // Attempt to combine to SHUFPS.
37803   if (AllowFloatDomain && EltSizeInBits == 32 &&
37804       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
37805        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
37806        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37807     SmallVector<int, 4> RepeatedMask;
37808     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
37809       // Match each half of the repeated mask, to determine if its just
37810       // referencing one of the vectors, is zeroable or entirely undef.
37811       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
37812         int M0 = RepeatedMask[Offset];
37813         int M1 = RepeatedMask[Offset + 1];
37814 
37815         if (isUndefInRange(RepeatedMask, Offset, 2)) {
37816           return DAG.getUNDEF(MaskVT);
37817         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
37818           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
37819           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
37820           return getZeroVector(MaskVT, Subtarget, DAG, DL);
37821         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
37822           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
37823           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
37824           return V1;
37825         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
37826           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
37827           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
37828           return V2;
37829         }
37830 
37831         return SDValue();
37832       };
37833 
37834       int ShufMask[4] = {-1, -1, -1, -1};
37835       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
37836       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
37837 
37838       if (Lo && Hi) {
37839         V1 = Lo;
37840         V2 = Hi;
37841         Shuffle = X86ISD::SHUFP;
37842         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
37843         PermuteImm = getV4X86ShuffleImm(ShufMask);
37844         return true;
37845       }
37846     }
37847   }
37848 
37849   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
37850   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
37851       MaskVT.is128BitVector() &&
37852       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
37853     Shuffle = X86ISD::INSERTPS;
37854     ShuffleVT = MVT::v4f32;
37855     return true;
37856   }
37857 
37858   return false;
37859 }
37860 
37861 static SDValue combineX86ShuffleChainWithExtract(
37862     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
37863     bool HasVariableMask, bool AllowVariableCrossLaneMask,
37864     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
37865     const X86Subtarget &Subtarget);
37866 
37867 /// Combine an arbitrary chain of shuffles into a single instruction if
37868 /// possible.
37869 ///
37870 /// This is the leaf of the recursive combine below. When we have found some
37871 /// chain of single-use x86 shuffle instructions and accumulated the combined
37872 /// shuffle mask represented by them, this will try to pattern match that mask
37873 /// into either a single instruction if there is a special purpose instruction
37874 /// for this operation, or into a PSHUFB instruction which is a fully general
37875 /// instruction but should only be used to replace chains over a certain depth.
37876 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
37877                                       ArrayRef<int> BaseMask, int Depth,
37878                                       bool HasVariableMask,
37879                                       bool AllowVariableCrossLaneMask,
37880                                       bool AllowVariablePerLaneMask,
37881                                       SelectionDAG &DAG,
37882                                       const X86Subtarget &Subtarget) {
37883   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
37884   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
37885          "Unexpected number of shuffle inputs!");
37886 
37887   SDLoc DL(Root);
37888   MVT RootVT = Root.getSimpleValueType();
37889   unsigned RootSizeInBits = RootVT.getSizeInBits();
37890   unsigned NumRootElts = RootVT.getVectorNumElements();
37891 
37892   // Canonicalize shuffle input op to the requested type.
37893   auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
37894     if (VT.getSizeInBits() > Op.getValueSizeInBits())
37895       Op = widenSubVector(Op, false, Subtarget, DAG, DL, VT.getSizeInBits());
37896     else if (VT.getSizeInBits() < Op.getValueSizeInBits())
37897       Op = extractSubVector(Op, 0, DAG, DL, VT.getSizeInBits());
37898     return DAG.getBitcast(VT, Op);
37899   };
37900 
37901   // Find the inputs that enter the chain. Note that multiple uses are OK
37902   // here, we're not going to remove the operands we find.
37903   bool UnaryShuffle = (Inputs.size() == 1);
37904   SDValue V1 = peekThroughBitcasts(Inputs[0]);
37905   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
37906                              : peekThroughBitcasts(Inputs[1]));
37907 
37908   MVT VT1 = V1.getSimpleValueType();
37909   MVT VT2 = V2.getSimpleValueType();
37910   assert((RootSizeInBits % VT1.getSizeInBits()) == 0 &&
37911          (RootSizeInBits % VT2.getSizeInBits()) == 0 && "Vector size mismatch");
37912 
37913   SDValue Res;
37914 
37915   unsigned NumBaseMaskElts = BaseMask.size();
37916   if (NumBaseMaskElts == 1) {
37917     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
37918     return CanonicalizeShuffleInput(RootVT, V1);
37919   }
37920 
37921   bool OptForSize = DAG.shouldOptForSize();
37922   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
37923   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
37924                      (RootVT.isFloatingPoint() && Depth >= 1) ||
37925                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
37926 
37927   // Don't combine if we are a AVX512/EVEX target and the mask element size
37928   // is different from the root element size - this would prevent writemasks
37929   // from being reused.
37930   bool IsMaskedShuffle = false;
37931   if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
37932     if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
37933         Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
37934       IsMaskedShuffle = true;
37935     }
37936   }
37937 
37938   // If we are shuffling a splat (and not introducing zeros) then we can just
37939   // use it directly. This works for smaller elements as well as they already
37940   // repeat across each mask element.
37941   if (UnaryShuffle && !isAnyZero(BaseMask) &&
37942       V1.getValueSizeInBits() >= RootSizeInBits &&
37943       (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
37944       DAG.isSplatValue(V1, /*AllowUndefs*/ false)) {
37945     return CanonicalizeShuffleInput(RootVT, V1);
37946   }
37947 
37948   SmallVector<int, 64> Mask(BaseMask.begin(), BaseMask.end());
37949 
37950   // See if the shuffle is a hidden identity shuffle - repeated args in HOPs
37951   // etc. can be simplified.
37952   if (VT1 == VT2 && VT1.getSizeInBits() == RootSizeInBits && VT1.isVector()) {
37953     SmallVector<int> ScaledMask, IdentityMask;
37954     unsigned NumElts = VT1.getVectorNumElements();
37955     if (Mask.size() <= NumElts &&
37956         scaleShuffleElements(Mask, NumElts, ScaledMask)) {
37957       for (unsigned i = 0; i != NumElts; ++i)
37958         IdentityMask.push_back(i);
37959       if (isTargetShuffleEquivalent(RootVT, ScaledMask, IdentityMask, DAG, V1,
37960                                     V2))
37961         return CanonicalizeShuffleInput(RootVT, V1);
37962     }
37963   }
37964 
37965   // Handle 128/256-bit lane shuffles of 512-bit vectors.
37966   if (RootVT.is512BitVector() &&
37967       (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
37968     // If the upper subvectors are zeroable, then an extract+insert is more
37969     // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
37970     // to zero the upper subvectors.
37971     if (isUndefOrZeroInRange(Mask, 1, NumBaseMaskElts - 1)) {
37972       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37973         return SDValue(); // Nothing to do!
37974       assert(isInRange(Mask[0], 0, NumBaseMaskElts) &&
37975              "Unexpected lane shuffle");
37976       Res = CanonicalizeShuffleInput(RootVT, V1);
37977       unsigned SubIdx = Mask[0] * (NumRootElts / NumBaseMaskElts);
37978       bool UseZero = isAnyZero(Mask);
37979       Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
37980       return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
37981     }
37982 
37983     // Narrow shuffle mask to v4x128.
37984     SmallVector<int, 4> ScaledMask;
37985     assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
37986     narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, Mask, ScaledMask);
37987 
37988     // Try to lower to vshuf64x2/vshuf32x4.
37989     auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL,
37990                             ArrayRef<int> ScaledMask, SDValue V1, SDValue V2,
37991                             SelectionDAG &DAG) {
37992       unsigned PermMask = 0;
37993       // Insure elements came from the same Op.
37994       SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
37995       for (int i = 0; i < 4; ++i) {
37996         assert(ScaledMask[i] >= -1 && "Illegal shuffle sentinel value");
37997         if (ScaledMask[i] < 0)
37998           continue;
37999 
38000         SDValue Op = ScaledMask[i] >= 4 ? V2 : V1;
38001         unsigned OpIndex = i / 2;
38002         if (Ops[OpIndex].isUndef())
38003           Ops[OpIndex] = Op;
38004         else if (Ops[OpIndex] != Op)
38005           return SDValue();
38006 
38007         // Convert the 128-bit shuffle mask selection values into 128-bit
38008         // selection bits defined by a vshuf64x2 instruction's immediate control
38009         // byte.
38010         PermMask |= (ScaledMask[i] % 4) << (i * 2);
38011       }
38012 
38013       return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
38014                          CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
38015                          CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
38016                          DAG.getTargetConstant(PermMask, DL, MVT::i8));
38017     };
38018 
38019     // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
38020     // doesn't work because our mask is for 128 bits and we don't have an MVT
38021     // to match that.
38022     bool PreferPERMQ = UnaryShuffle && isUndefOrInRange(ScaledMask[0], 0, 2) &&
38023                        isUndefOrInRange(ScaledMask[1], 0, 2) &&
38024                        isUndefOrInRange(ScaledMask[2], 2, 4) &&
38025                        isUndefOrInRange(ScaledMask[3], 2, 4) &&
38026                        (ScaledMask[0] < 0 || ScaledMask[2] < 0 ||
38027                         ScaledMask[0] == (ScaledMask[2] % 2)) &&
38028                        (ScaledMask[1] < 0 || ScaledMask[3] < 0 ||
38029                         ScaledMask[1] == (ScaledMask[3] % 2));
38030 
38031     if (!isAnyZero(ScaledMask) && !PreferPERMQ) {
38032       if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
38033         return SDValue(); // Nothing to do!
38034       MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
38035       if (SDValue V = MatchSHUF128(ShuffleVT, DL, ScaledMask, V1, V2, DAG))
38036         return DAG.getBitcast(RootVT, V);
38037     }
38038   }
38039 
38040   // Handle 128-bit lane shuffles of 256-bit vectors.
38041   if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
38042     // If the upper half is zeroable, then an extract+insert is more optimal
38043     // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
38044     // zero the upper half.
38045     if (isUndefOrZero(Mask[1])) {
38046       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
38047         return SDValue(); // Nothing to do!
38048       assert(isInRange(Mask[0], 0, 2) && "Unexpected lane shuffle");
38049       Res = CanonicalizeShuffleInput(RootVT, V1);
38050       Res = extract128BitVector(Res, Mask[0] * (NumRootElts / 2), DAG, DL);
38051       return widenSubVector(Res, Mask[1] == SM_SentinelZero, Subtarget, DAG, DL,
38052                             256);
38053     }
38054 
38055     // If we're inserting the low subvector, an insert-subvector 'concat'
38056     // pattern is quicker than VPERM2X128.
38057     // TODO: Add AVX2 support instead of VPERMQ/VPERMPD.
38058     if (BaseMask[0] == 0 && (BaseMask[1] == 0 || BaseMask[1] == 2) &&
38059         !Subtarget.hasAVX2()) {
38060       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
38061         return SDValue(); // Nothing to do!
38062       SDValue Lo = CanonicalizeShuffleInput(RootVT, V1);
38063       SDValue Hi = CanonicalizeShuffleInput(RootVT, BaseMask[1] == 0 ? V1 : V2);
38064       Hi = extractSubVector(Hi, 0, DAG, DL, 128);
38065       return insertSubVector(Lo, Hi, NumRootElts / 2, DAG, DL, 128);
38066     }
38067 
38068     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
38069       return SDValue(); // Nothing to do!
38070 
38071     // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
38072     // we need to use the zeroing feature.
38073     // Prefer blends for sequential shuffles unless we are optimizing for size.
38074     if (UnaryShuffle &&
38075         !(Subtarget.hasAVX2() && isUndefOrInRange(Mask, 0, 2)) &&
38076         (OptForSize || !isSequentialOrUndefOrZeroInRange(Mask, 0, 2, 0))) {
38077       unsigned PermMask = 0;
38078       PermMask |= ((Mask[0] < 0 ? 0x8 : (Mask[0] & 1)) << 0);
38079       PermMask |= ((Mask[1] < 0 ? 0x8 : (Mask[1] & 1)) << 4);
38080       return DAG.getNode(
38081           X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
38082           DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
38083     }
38084 
38085     if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
38086       return SDValue(); // Nothing to do!
38087 
38088     // TODO - handle AVX512VL cases with X86ISD::SHUF128.
38089     if (!UnaryShuffle && !IsMaskedShuffle) {
38090       assert(llvm::all_of(Mask, [](int M) { return 0 <= M && M < 4; }) &&
38091              "Unexpected shuffle sentinel value");
38092       // Prefer blends to X86ISD::VPERM2X128.
38093       if (!((Mask[0] == 0 && Mask[1] == 3) || (Mask[0] == 2 && Mask[1] == 1))) {
38094         unsigned PermMask = 0;
38095         PermMask |= ((Mask[0] & 3) << 0);
38096         PermMask |= ((Mask[1] & 3) << 4);
38097         SDValue LHS = isInRange(Mask[0], 0, 2) ? V1 : V2;
38098         SDValue RHS = isInRange(Mask[1], 0, 2) ? V1 : V2;
38099         return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
38100                           CanonicalizeShuffleInput(RootVT, LHS),
38101                           CanonicalizeShuffleInput(RootVT, RHS),
38102                           DAG.getTargetConstant(PermMask, DL, MVT::i8));
38103       }
38104     }
38105   }
38106 
38107   // For masks that have been widened to 128-bit elements or more,
38108   // narrow back down to 64-bit elements.
38109   if (BaseMaskEltSizeInBits > 64) {
38110     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
38111     int MaskScale = BaseMaskEltSizeInBits / 64;
38112     SmallVector<int, 64> ScaledMask;
38113     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
38114     Mask = std::move(ScaledMask);
38115   }
38116 
38117   // For masked shuffles, we're trying to match the root width for better
38118   // writemask folding, attempt to scale the mask.
38119   // TODO - variable shuffles might need this to be widened again.
38120   if (IsMaskedShuffle && NumRootElts > Mask.size()) {
38121     assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
38122     int MaskScale = NumRootElts / Mask.size();
38123     SmallVector<int, 64> ScaledMask;
38124     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
38125     Mask = std::move(ScaledMask);
38126   }
38127 
38128   unsigned NumMaskElts = Mask.size();
38129   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
38130 
38131   // Determine the effective mask value type.
38132   FloatDomain &= (32 <= MaskEltSizeInBits);
38133   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
38134                            : MVT::getIntegerVT(MaskEltSizeInBits);
38135   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
38136 
38137   // Only allow legal mask types.
38138   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
38139     return SDValue();
38140 
38141   // Attempt to match the mask against known shuffle patterns.
38142   MVT ShuffleSrcVT, ShuffleVT;
38143   unsigned Shuffle, PermuteImm;
38144 
38145   // Which shuffle domains are permitted?
38146   // Permit domain crossing at higher combine depths.
38147   // TODO: Should we indicate which domain is preferred if both are allowed?
38148   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
38149   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
38150                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
38151 
38152   // Determine zeroable mask elements.
38153   APInt KnownUndef, KnownZero;
38154   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
38155   APInt Zeroable = KnownUndef | KnownZero;
38156 
38157   if (UnaryShuffle) {
38158     // Attempt to match against broadcast-from-vector.
38159     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
38160     if ((Subtarget.hasAVX2() ||
38161          (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
38162         (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
38163       if (isUndefOrEqual(Mask, 0)) {
38164         if (V1.getValueType() == MaskVT &&
38165             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
38166             X86::mayFoldLoad(V1.getOperand(0), Subtarget)) {
38167           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
38168             return SDValue(); // Nothing to do!
38169           Res = V1.getOperand(0);
38170           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
38171           return DAG.getBitcast(RootVT, Res);
38172         }
38173         if (Subtarget.hasAVX2()) {
38174           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
38175             return SDValue(); // Nothing to do!
38176           Res = CanonicalizeShuffleInput(MaskVT, V1);
38177           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
38178           return DAG.getBitcast(RootVT, Res);
38179         }
38180       }
38181     }
38182 
38183     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, V1,
38184                           DAG, Subtarget, Shuffle, ShuffleSrcVT, ShuffleVT) &&
38185         (!IsMaskedShuffle ||
38186          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38187       if (Depth == 0 && Root.getOpcode() == Shuffle)
38188         return SDValue(); // Nothing to do!
38189       Res = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
38190       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
38191       return DAG.getBitcast(RootVT, Res);
38192     }
38193 
38194     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
38195                                  AllowIntDomain, DAG, Subtarget, Shuffle, ShuffleVT,
38196                                  PermuteImm) &&
38197         (!IsMaskedShuffle ||
38198          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38199       if (Depth == 0 && Root.getOpcode() == Shuffle)
38200         return SDValue(); // Nothing to do!
38201       Res = CanonicalizeShuffleInput(ShuffleVT, V1);
38202       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
38203                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38204       return DAG.getBitcast(RootVT, Res);
38205     }
38206   }
38207 
38208   // Attempt to combine to INSERTPS, but only if the inserted element has come
38209   // from a scalar.
38210   // TODO: Handle other insertions here as well?
38211   if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
38212       Subtarget.hasSSE41() &&
38213       !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG)) {
38214     if (MaskEltSizeInBits == 32) {
38215       SDValue SrcV1 = V1, SrcV2 = V2;
38216       if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
38217                                  DAG) &&
38218           SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
38219         if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
38220           return SDValue(); // Nothing to do!
38221         Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
38222                           CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
38223                           CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
38224                           DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38225         return DAG.getBitcast(RootVT, Res);
38226       }
38227     }
38228     if (MaskEltSizeInBits == 64 &&
38229         isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}, DAG) &&
38230         V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
38231         V2.getScalarValueSizeInBits() <= 32) {
38232       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
38233         return SDValue(); // Nothing to do!
38234       PermuteImm = (/*DstIdx*/ 2 << 4) | (/*SrcIdx*/ 0 << 0);
38235       Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
38236                         CanonicalizeShuffleInput(MVT::v4f32, V1),
38237                         CanonicalizeShuffleInput(MVT::v4f32, V2),
38238                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38239       return DAG.getBitcast(RootVT, Res);
38240     }
38241   }
38242 
38243   SDValue NewV1 = V1; // Save operands in case early exit happens.
38244   SDValue NewV2 = V2;
38245   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
38246                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
38247                          ShuffleVT, UnaryShuffle) &&
38248       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38249     if (Depth == 0 && Root.getOpcode() == Shuffle)
38250       return SDValue(); // Nothing to do!
38251     NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
38252     NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
38253     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
38254     return DAG.getBitcast(RootVT, Res);
38255   }
38256 
38257   NewV1 = V1; // Save operands in case early exit happens.
38258   NewV2 = V2;
38259   if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
38260                                 AllowIntDomain, NewV1, NewV2, DL, DAG,
38261                                 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
38262       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38263     if (Depth == 0 && Root.getOpcode() == Shuffle)
38264       return SDValue(); // Nothing to do!
38265     NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
38266     NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
38267     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
38268                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38269     return DAG.getBitcast(RootVT, Res);
38270   }
38271 
38272   // Typically from here on, we need an integer version of MaskVT.
38273   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
38274   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
38275 
38276   // Annoyingly, SSE4A instructions don't map into the above match helpers.
38277   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
38278     uint64_t BitLen, BitIdx;
38279     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
38280                             Zeroable)) {
38281       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
38282         return SDValue(); // Nothing to do!
38283       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
38284       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
38285                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
38286                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
38287       return DAG.getBitcast(RootVT, Res);
38288     }
38289 
38290     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
38291       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
38292         return SDValue(); // Nothing to do!
38293       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
38294       V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
38295       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
38296                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
38297                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
38298       return DAG.getBitcast(RootVT, Res);
38299     }
38300   }
38301 
38302   // Match shuffle against TRUNCATE patterns.
38303   if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
38304     // Match against a VTRUNC instruction, accounting for src/dst sizes.
38305     if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
38306                              Subtarget)) {
38307       bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
38308                         ShuffleSrcVT.getVectorNumElements();
38309       unsigned Opc =
38310           IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
38311       if (Depth == 0 && Root.getOpcode() == Opc)
38312         return SDValue(); // Nothing to do!
38313       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
38314       Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
38315       if (ShuffleVT.getSizeInBits() < RootSizeInBits)
38316         Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
38317       return DAG.getBitcast(RootVT, Res);
38318     }
38319 
38320     // Do we need a more general binary truncation pattern?
38321     if (RootSizeInBits < 512 &&
38322         ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
38323          (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
38324         (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
38325         isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
38326       // Bail if this was already a truncation or PACK node.
38327       // We sometimes fail to match PACK if we demand known undef elements.
38328       if (Depth == 0 && (Root.getOpcode() == ISD::TRUNCATE ||
38329                          Root.getOpcode() == X86ISD::PACKSS ||
38330                          Root.getOpcode() == X86ISD::PACKUS))
38331         return SDValue(); // Nothing to do!
38332       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
38333       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
38334       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
38335       V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
38336       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
38337       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
38338       Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
38339       Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
38340       return DAG.getBitcast(RootVT, Res);
38341     }
38342   }
38343 
38344   // Don't try to re-form single instruction chains under any circumstances now
38345   // that we've done encoding canonicalization for them.
38346   if (Depth < 1)
38347     return SDValue();
38348 
38349   // Depth threshold above which we can efficiently use variable mask shuffles.
38350   int VariableCrossLaneShuffleDepth =
38351       Subtarget.hasFastVariableCrossLaneShuffle() ? 1 : 2;
38352   int VariablePerLaneShuffleDepth =
38353       Subtarget.hasFastVariablePerLaneShuffle() ? 1 : 2;
38354   AllowVariableCrossLaneMask &=
38355       (Depth >= VariableCrossLaneShuffleDepth) || HasVariableMask;
38356   AllowVariablePerLaneMask &=
38357       (Depth >= VariablePerLaneShuffleDepth) || HasVariableMask;
38358   // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
38359   // higher depth before combining them.
38360   bool AllowBWIVPERMV3 =
38361       (Depth >= (VariableCrossLaneShuffleDepth + 2) || HasVariableMask);
38362 
38363   bool MaskContainsZeros = isAnyZero(Mask);
38364 
38365   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
38366     // If we have a single input lane-crossing shuffle then lower to VPERMV.
38367     if (UnaryShuffle && AllowVariableCrossLaneMask && !MaskContainsZeros) {
38368       if (Subtarget.hasAVX2() &&
38369           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
38370         SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
38371         Res = CanonicalizeShuffleInput(MaskVT, V1);
38372         Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
38373         return DAG.getBitcast(RootVT, Res);
38374       }
38375       // AVX512 variants (non-VLX will pad to 512-bit shuffles).
38376       if ((Subtarget.hasAVX512() &&
38377            (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
38378             MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
38379           (Subtarget.hasBWI() &&
38380            (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
38381           (Subtarget.hasVBMI() &&
38382            (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
38383         V1 = CanonicalizeShuffleInput(MaskVT, V1);
38384         V2 = DAG.getUNDEF(MaskVT);
38385         Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38386         return DAG.getBitcast(RootVT, Res);
38387       }
38388     }
38389 
38390     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
38391     // vector as the second source (non-VLX will pad to 512-bit shuffles).
38392     if (UnaryShuffle && AllowVariableCrossLaneMask &&
38393         ((Subtarget.hasAVX512() &&
38394           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
38395            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
38396            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
38397            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
38398          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
38399           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
38400          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
38401           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
38402       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
38403       for (unsigned i = 0; i != NumMaskElts; ++i)
38404         if (Mask[i] == SM_SentinelZero)
38405           Mask[i] = NumMaskElts + i;
38406       V1 = CanonicalizeShuffleInput(MaskVT, V1);
38407       V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
38408       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38409       return DAG.getBitcast(RootVT, Res);
38410     }
38411 
38412     // If that failed and either input is extracted then try to combine as a
38413     // shuffle with the larger type.
38414     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
38415             Inputs, Root, BaseMask, Depth, HasVariableMask,
38416             AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG,
38417             Subtarget))
38418       return WideShuffle;
38419 
38420     // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
38421     // (non-VLX will pad to 512-bit shuffles).
38422     if (AllowVariableCrossLaneMask && !MaskContainsZeros &&
38423         ((Subtarget.hasAVX512() &&
38424           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
38425            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
38426            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
38427            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
38428          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
38429           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
38430          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
38431           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
38432       V1 = CanonicalizeShuffleInput(MaskVT, V1);
38433       V2 = CanonicalizeShuffleInput(MaskVT, V2);
38434       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38435       return DAG.getBitcast(RootVT, Res);
38436     }
38437     return SDValue();
38438   }
38439 
38440   // See if we can combine a single input shuffle with zeros to a bit-mask,
38441   // which is much simpler than any shuffle.
38442   if (UnaryShuffle && MaskContainsZeros && AllowVariablePerLaneMask &&
38443       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
38444       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
38445     APInt Zero = APInt::getZero(MaskEltSizeInBits);
38446     APInt AllOnes = APInt::getAllOnes(MaskEltSizeInBits);
38447     APInt UndefElts(NumMaskElts, 0);
38448     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
38449     for (unsigned i = 0; i != NumMaskElts; ++i) {
38450       int M = Mask[i];
38451       if (M == SM_SentinelUndef) {
38452         UndefElts.setBit(i);
38453         continue;
38454       }
38455       if (M == SM_SentinelZero)
38456         continue;
38457       EltBits[i] = AllOnes;
38458     }
38459     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
38460     Res = CanonicalizeShuffleInput(MaskVT, V1);
38461     unsigned AndOpcode =
38462         MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
38463     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
38464     return DAG.getBitcast(RootVT, Res);
38465   }
38466 
38467   // If we have a single input shuffle with different shuffle patterns in the
38468   // the 128-bit lanes use the variable mask to VPERMILPS.
38469   // TODO Combine other mask types at higher depths.
38470   if (UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
38471       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
38472        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
38473     SmallVector<SDValue, 16> VPermIdx;
38474     for (int M : Mask) {
38475       SDValue Idx =
38476           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
38477       VPermIdx.push_back(Idx);
38478     }
38479     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
38480     Res = CanonicalizeShuffleInput(MaskVT, V1);
38481     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
38482     return DAG.getBitcast(RootVT, Res);
38483   }
38484 
38485   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
38486   // to VPERMIL2PD/VPERMIL2PS.
38487   if (AllowVariablePerLaneMask && Subtarget.hasXOP() &&
38488       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
38489        MaskVT == MVT::v8f32)) {
38490     // VPERMIL2 Operation.
38491     // Bits[3] - Match Bit.
38492     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
38493     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
38494     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
38495     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
38496     SmallVector<int, 8> VPerm2Idx;
38497     unsigned M2ZImm = 0;
38498     for (int M : Mask) {
38499       if (M == SM_SentinelUndef) {
38500         VPerm2Idx.push_back(-1);
38501         continue;
38502       }
38503       if (M == SM_SentinelZero) {
38504         M2ZImm = 2;
38505         VPerm2Idx.push_back(8);
38506         continue;
38507       }
38508       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
38509       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
38510       VPerm2Idx.push_back(Index);
38511     }
38512     V1 = CanonicalizeShuffleInput(MaskVT, V1);
38513     V2 = CanonicalizeShuffleInput(MaskVT, V2);
38514     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
38515     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
38516                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
38517     return DAG.getBitcast(RootVT, Res);
38518   }
38519 
38520   // If we have 3 or more shuffle instructions or a chain involving a variable
38521   // mask, we can replace them with a single PSHUFB instruction profitably.
38522   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
38523   // instructions, but in practice PSHUFB tends to be *very* fast so we're
38524   // more aggressive.
38525   if (UnaryShuffle && AllowVariablePerLaneMask &&
38526       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
38527        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
38528        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
38529     SmallVector<SDValue, 16> PSHUFBMask;
38530     int NumBytes = RootVT.getSizeInBits() / 8;
38531     int Ratio = NumBytes / NumMaskElts;
38532     for (int i = 0; i < NumBytes; ++i) {
38533       int M = Mask[i / Ratio];
38534       if (M == SM_SentinelUndef) {
38535         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
38536         continue;
38537       }
38538       if (M == SM_SentinelZero) {
38539         PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
38540         continue;
38541       }
38542       M = Ratio * M + i % Ratio;
38543       assert((M / 16) == (i / 16) && "Lane crossing detected");
38544       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
38545     }
38546     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
38547     Res = CanonicalizeShuffleInput(ByteVT, V1);
38548     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
38549     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
38550     return DAG.getBitcast(RootVT, Res);
38551   }
38552 
38553   // With XOP, if we have a 128-bit binary input shuffle we can always combine
38554   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
38555   // slower than PSHUFB on targets that support both.
38556   if (AllowVariablePerLaneMask && RootVT.is128BitVector() &&
38557       Subtarget.hasXOP()) {
38558     // VPPERM Mask Operation
38559     // Bits[4:0] - Byte Index (0 - 31)
38560     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
38561     SmallVector<SDValue, 16> VPPERMMask;
38562     int NumBytes = 16;
38563     int Ratio = NumBytes / NumMaskElts;
38564     for (int i = 0; i < NumBytes; ++i) {
38565       int M = Mask[i / Ratio];
38566       if (M == SM_SentinelUndef) {
38567         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
38568         continue;
38569       }
38570       if (M == SM_SentinelZero) {
38571         VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
38572         continue;
38573       }
38574       M = Ratio * M + i % Ratio;
38575       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
38576     }
38577     MVT ByteVT = MVT::v16i8;
38578     V1 = CanonicalizeShuffleInput(ByteVT, V1);
38579     V2 = CanonicalizeShuffleInput(ByteVT, V2);
38580     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
38581     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
38582     return DAG.getBitcast(RootVT, Res);
38583   }
38584 
38585   // If that failed and either input is extracted then try to combine as a
38586   // shuffle with the larger type.
38587   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
38588           Inputs, Root, BaseMask, Depth, HasVariableMask,
38589           AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG, Subtarget))
38590     return WideShuffle;
38591 
38592   // If we have a dual input shuffle then lower to VPERMV3,
38593   // (non-VLX will pad to 512-bit shuffles)
38594   if (!UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
38595       ((Subtarget.hasAVX512() &&
38596         (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
38597          MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
38598          MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
38599          MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
38600          MaskVT == MVT::v16i32)) ||
38601        (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
38602         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 ||
38603          MaskVT == MVT::v32i16)) ||
38604        (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
38605         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 ||
38606          MaskVT == MVT::v64i8)))) {
38607     V1 = CanonicalizeShuffleInput(MaskVT, V1);
38608     V2 = CanonicalizeShuffleInput(MaskVT, V2);
38609     Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38610     return DAG.getBitcast(RootVT, Res);
38611   }
38612 
38613   // Failed to find any combines.
38614   return SDValue();
38615 }
38616 
38617 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
38618 // instruction if possible.
38619 //
38620 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
38621 // type size to attempt to combine:
38622 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
38623 // -->
38624 // extract_subvector(shuffle(x,y,m2),0)
38625 static SDValue combineX86ShuffleChainWithExtract(
38626     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
38627     bool HasVariableMask, bool AllowVariableCrossLaneMask,
38628     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
38629     const X86Subtarget &Subtarget) {
38630   unsigned NumMaskElts = BaseMask.size();
38631   unsigned NumInputs = Inputs.size();
38632   if (NumInputs == 0)
38633     return SDValue();
38634 
38635   EVT RootVT = Root.getValueType();
38636   unsigned RootSizeInBits = RootVT.getSizeInBits();
38637   assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask");
38638 
38639   // Bail if we have any smaller inputs.
38640   if (llvm::any_of(Inputs, [RootSizeInBits](SDValue Input) {
38641         return Input.getValueSizeInBits() < RootSizeInBits;
38642       }))
38643     return SDValue();
38644 
38645   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
38646   SmallVector<unsigned, 4> Offsets(NumInputs, 0);
38647 
38648   // Peek through subvectors.
38649   // TODO: Support inter-mixed EXTRACT_SUBVECTORs + BITCASTs?
38650   unsigned WideSizeInBits = RootSizeInBits;
38651   for (unsigned i = 0; i != NumInputs; ++i) {
38652     SDValue &Src = WideInputs[i];
38653     unsigned &Offset = Offsets[i];
38654     Src = peekThroughBitcasts(Src);
38655     EVT BaseVT = Src.getValueType();
38656     while (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
38657       Offset += Src.getConstantOperandVal(1);
38658       Src = Src.getOperand(0);
38659     }
38660     WideSizeInBits = std::max(WideSizeInBits,
38661                               (unsigned)Src.getValueSizeInBits());
38662     assert((Offset % BaseVT.getVectorNumElements()) == 0 &&
38663            "Unexpected subvector extraction");
38664     Offset /= BaseVT.getVectorNumElements();
38665     Offset *= NumMaskElts;
38666   }
38667 
38668   // Bail if we're always extracting from the lowest subvectors,
38669   // combineX86ShuffleChain should match this for the current width.
38670   if (llvm::all_of(Offsets, [](unsigned Offset) { return Offset == 0; }))
38671     return SDValue();
38672 
38673   unsigned Scale = WideSizeInBits / RootSizeInBits;
38674   assert((WideSizeInBits % RootSizeInBits) == 0 &&
38675          "Unexpected subvector extraction");
38676 
38677   // If the src vector types aren't the same, see if we can extend
38678   // them to match each other.
38679   // TODO: Support different scalar types?
38680   EVT WideSVT = WideInputs[0].getValueType().getScalarType();
38681   if (llvm::any_of(WideInputs, [&WideSVT, &DAG](SDValue Op) {
38682         return !DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()) ||
38683                Op.getValueType().getScalarType() != WideSVT;
38684       }))
38685     return SDValue();
38686 
38687   // Create new mask for larger type.
38688   for (unsigned i = 1; i != NumInputs; ++i)
38689     Offsets[i] += i * Scale * NumMaskElts;
38690 
38691   SmallVector<int, 64> WideMask(BaseMask.begin(), BaseMask.end());
38692   for (int &M : WideMask) {
38693     if (M < 0)
38694       continue;
38695     M = (M % NumMaskElts) + Offsets[M / NumMaskElts];
38696   }
38697   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
38698 
38699   // Remove unused/repeated shuffle source ops.
38700   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
38701   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
38702 
38703   if (WideInputs.size() > 2)
38704     return SDValue();
38705 
38706   // Increase depth for every upper subvector we've peeked through.
38707   Depth += count_if(Offsets, [](unsigned Offset) { return Offset > 0; });
38708 
38709   // Attempt to combine wider chain.
38710   // TODO: Can we use a better Root?
38711   SDValue WideRoot = WideInputs.front().getValueSizeInBits() >
38712                              WideInputs.back().getValueSizeInBits()
38713                          ? WideInputs.front()
38714                          : WideInputs.back();
38715   if (SDValue WideShuffle =
38716           combineX86ShuffleChain(WideInputs, WideRoot, WideMask, Depth,
38717                                  HasVariableMask, AllowVariableCrossLaneMask,
38718                                  AllowVariablePerLaneMask, DAG, Subtarget)) {
38719     WideShuffle =
38720         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
38721     return DAG.getBitcast(RootVT, WideShuffle);
38722   }
38723   return SDValue();
38724 }
38725 
38726 // Canonicalize the combined shuffle mask chain with horizontal ops.
38727 // NOTE: This may update the Ops and Mask.
38728 static SDValue canonicalizeShuffleMaskWithHorizOp(
38729     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
38730     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
38731     const X86Subtarget &Subtarget) {
38732   if (Mask.empty() || Ops.empty())
38733     return SDValue();
38734 
38735   SmallVector<SDValue> BC;
38736   for (SDValue Op : Ops)
38737     BC.push_back(peekThroughBitcasts(Op));
38738 
38739   // All ops must be the same horizop + type.
38740   SDValue BC0 = BC[0];
38741   EVT VT0 = BC0.getValueType();
38742   unsigned Opcode0 = BC0.getOpcode();
38743   if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
38744         return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
38745       }))
38746     return SDValue();
38747 
38748   bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
38749                   Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
38750   bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
38751   if (!isHoriz && !isPack)
38752     return SDValue();
38753 
38754   // Do all ops have a single use?
38755   bool OneUseOps = llvm::all_of(Ops, [](SDValue Op) {
38756     return Op.hasOneUse() &&
38757            peekThroughBitcasts(Op) == peekThroughOneUseBitcasts(Op);
38758   });
38759 
38760   int NumElts = VT0.getVectorNumElements();
38761   int NumLanes = VT0.getSizeInBits() / 128;
38762   int NumEltsPerLane = NumElts / NumLanes;
38763   int NumHalfEltsPerLane = NumEltsPerLane / 2;
38764   MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
38765   unsigned EltSizeInBits = RootSizeInBits / Mask.size();
38766 
38767   if (NumEltsPerLane >= 4 &&
38768       (isPack || shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget))) {
38769     SmallVector<int> LaneMask, ScaledMask;
38770     if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, LaneMask) &&
38771         scaleShuffleElements(LaneMask, 4, ScaledMask)) {
38772       // See if we can remove the shuffle by resorting the HOP chain so that
38773       // the HOP args are pre-shuffled.
38774       // TODO: Generalize to any sized/depth chain.
38775       // TODO: Add support for PACKSS/PACKUS.
38776       if (isHoriz) {
38777         // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
38778         auto GetHOpSrc = [&](int M) {
38779           if (M == SM_SentinelUndef)
38780             return DAG.getUNDEF(VT0);
38781           if (M == SM_SentinelZero)
38782             return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
38783           SDValue Src0 = BC[M / 4];
38784           SDValue Src1 = Src0.getOperand((M % 4) >= 2);
38785           if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
38786             return Src1.getOperand(M % 2);
38787           return SDValue();
38788         };
38789         SDValue M0 = GetHOpSrc(ScaledMask[0]);
38790         SDValue M1 = GetHOpSrc(ScaledMask[1]);
38791         SDValue M2 = GetHOpSrc(ScaledMask[2]);
38792         SDValue M3 = GetHOpSrc(ScaledMask[3]);
38793         if (M0 && M1 && M2 && M3) {
38794           SDValue LHS = DAG.getNode(Opcode0, DL, SrcVT, M0, M1);
38795           SDValue RHS = DAG.getNode(Opcode0, DL, SrcVT, M2, M3);
38796           return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
38797         }
38798       }
38799       // shuffle(hop(x,y),hop(z,w)) -> permute(hop(x,z)) etc.
38800       if (Ops.size() >= 2) {
38801         SDValue LHS, RHS;
38802         auto GetHOpSrc = [&](int M, int &OutM) {
38803           // TODO: Support SM_SentinelZero
38804           if (M < 0)
38805             return M == SM_SentinelUndef;
38806           SDValue Src = BC[M / 4].getOperand((M % 4) >= 2);
38807           if (!LHS || LHS == Src) {
38808             LHS = Src;
38809             OutM = (M % 2);
38810             return true;
38811           }
38812           if (!RHS || RHS == Src) {
38813             RHS = Src;
38814             OutM = (M % 2) + 2;
38815             return true;
38816           }
38817           return false;
38818         };
38819         int PostMask[4] = {-1, -1, -1, -1};
38820         if (GetHOpSrc(ScaledMask[0], PostMask[0]) &&
38821             GetHOpSrc(ScaledMask[1], PostMask[1]) &&
38822             GetHOpSrc(ScaledMask[2], PostMask[2]) &&
38823             GetHOpSrc(ScaledMask[3], PostMask[3])) {
38824           LHS = DAG.getBitcast(SrcVT, LHS);
38825           RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
38826           SDValue Res = DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
38827           // Use SHUFPS for the permute so this will work on SSE3 targets,
38828           // shuffle combining and domain handling will simplify this later on.
38829           MVT ShuffleVT = MVT::getVectorVT(MVT::f32, RootSizeInBits / 32);
38830           Res = DAG.getBitcast(ShuffleVT, Res);
38831           return DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
38832                              getV4X86ShuffleImm8ForMask(PostMask, DL, DAG));
38833         }
38834       }
38835     }
38836   }
38837 
38838   if (2 < Ops.size())
38839     return SDValue();
38840 
38841   SDValue BC1 = BC[BC.size() - 1];
38842   if (Mask.size() == VT0.getVectorNumElements()) {
38843     // Canonicalize binary shuffles of horizontal ops that use the
38844     // same sources to an unary shuffle.
38845     // TODO: Try to perform this fold even if the shuffle remains.
38846     if (Ops.size() == 2) {
38847       auto ContainsOps = [](SDValue HOp, SDValue Op) {
38848         return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
38849       };
38850       // Commute if all BC0's ops are contained in BC1.
38851       if (ContainsOps(BC1, BC0.getOperand(0)) &&
38852           ContainsOps(BC1, BC0.getOperand(1))) {
38853         ShuffleVectorSDNode::commuteMask(Mask);
38854         std::swap(Ops[0], Ops[1]);
38855         std::swap(BC0, BC1);
38856       }
38857 
38858       // If BC1 can be represented by BC0, then convert to unary shuffle.
38859       if (ContainsOps(BC0, BC1.getOperand(0)) &&
38860           ContainsOps(BC0, BC1.getOperand(1))) {
38861         for (int &M : Mask) {
38862           if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
38863             continue;
38864           int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
38865           M -= NumElts + (SubLane * NumHalfEltsPerLane);
38866           if (BC1.getOperand(SubLane) != BC0.getOperand(0))
38867             M += NumHalfEltsPerLane;
38868         }
38869       }
38870     }
38871 
38872     // Canonicalize unary horizontal ops to only refer to lower halves.
38873     for (int i = 0; i != NumElts; ++i) {
38874       int &M = Mask[i];
38875       if (isUndefOrZero(M))
38876         continue;
38877       if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
38878           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
38879         M -= NumHalfEltsPerLane;
38880       if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
38881           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
38882         M -= NumHalfEltsPerLane;
38883     }
38884   }
38885 
38886   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
38887   // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
38888   // represents the LHS/RHS inputs for the lower/upper halves.
38889   SmallVector<int, 16> TargetMask128, WideMask128;
38890   if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
38891       scaleShuffleElements(TargetMask128, 2, WideMask128)) {
38892     assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle");
38893     bool SingleOp = (Ops.size() == 1);
38894     if (isPack || OneUseOps ||
38895         shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
38896       SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
38897       SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
38898       Lo = Lo.getOperand(WideMask128[0] & 1);
38899       Hi = Hi.getOperand(WideMask128[1] & 1);
38900       if (SingleOp) {
38901         SDValue Undef = DAG.getUNDEF(SrcVT);
38902         SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
38903         Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
38904         Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
38905         Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
38906         Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
38907       }
38908       return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
38909     }
38910   }
38911 
38912   return SDValue();
38913 }
38914 
38915 // Attempt to constant fold all of the constant source ops.
38916 // Returns true if the entire shuffle is folded to a constant.
38917 // TODO: Extend this to merge multiple constant Ops and update the mask.
38918 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
38919                                            ArrayRef<int> Mask, SDValue Root,
38920                                            bool HasVariableMask,
38921                                            SelectionDAG &DAG,
38922                                            const X86Subtarget &Subtarget) {
38923   MVT VT = Root.getSimpleValueType();
38924 
38925   unsigned SizeInBits = VT.getSizeInBits();
38926   unsigned NumMaskElts = Mask.size();
38927   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
38928   unsigned NumOps = Ops.size();
38929 
38930   // Extract constant bits from each source op.
38931   bool OneUseConstantOp = false;
38932   SmallVector<APInt, 16> UndefEltsOps(NumOps);
38933   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
38934   for (unsigned i = 0; i != NumOps; ++i) {
38935     SDValue SrcOp = Ops[i];
38936     OneUseConstantOp |= SrcOp.hasOneUse();
38937     if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
38938                                        RawBitsOps[i]))
38939       return SDValue();
38940   }
38941 
38942   // If we're optimizing for size, only fold if at least one of the constants is
38943   // only used once or the combined shuffle has included a variable mask
38944   // shuffle, this is to avoid constant pool bloat.
38945   bool IsOptimizingSize = DAG.shouldOptForSize();
38946   if (IsOptimizingSize && !OneUseConstantOp && !HasVariableMask)
38947     return SDValue();
38948 
38949   // Shuffle the constant bits according to the mask.
38950   SDLoc DL(Root);
38951   APInt UndefElts(NumMaskElts, 0);
38952   APInt ZeroElts(NumMaskElts, 0);
38953   APInt ConstantElts(NumMaskElts, 0);
38954   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
38955                                         APInt::getZero(MaskSizeInBits));
38956   for (unsigned i = 0; i != NumMaskElts; ++i) {
38957     int M = Mask[i];
38958     if (M == SM_SentinelUndef) {
38959       UndefElts.setBit(i);
38960       continue;
38961     } else if (M == SM_SentinelZero) {
38962       ZeroElts.setBit(i);
38963       continue;
38964     }
38965     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
38966 
38967     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
38968     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
38969 
38970     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
38971     if (SrcUndefElts[SrcMaskIdx]) {
38972       UndefElts.setBit(i);
38973       continue;
38974     }
38975 
38976     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
38977     APInt &Bits = SrcEltBits[SrcMaskIdx];
38978     if (!Bits) {
38979       ZeroElts.setBit(i);
38980       continue;
38981     }
38982 
38983     ConstantElts.setBit(i);
38984     ConstantBitData[i] = Bits;
38985   }
38986   assert((UndefElts | ZeroElts | ConstantElts).isAllOnes());
38987 
38988   // Attempt to create a zero vector.
38989   if ((UndefElts | ZeroElts).isAllOnes())
38990     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
38991 
38992   // Create the constant data.
38993   MVT MaskSVT;
38994   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
38995     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
38996   else
38997     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
38998 
38999   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
39000   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
39001     return SDValue();
39002 
39003   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
39004   return DAG.getBitcast(VT, CstOp);
39005 }
39006 
39007 namespace llvm {
39008   namespace X86 {
39009     enum {
39010       MaxShuffleCombineDepth = 8
39011     };
39012   }
39013 } // namespace llvm
39014 
39015 /// Fully generic combining of x86 shuffle instructions.
39016 ///
39017 /// This should be the last combine run over the x86 shuffle instructions. Once
39018 /// they have been fully optimized, this will recursively consider all chains
39019 /// of single-use shuffle instructions, build a generic model of the cumulative
39020 /// shuffle operation, and check for simpler instructions which implement this
39021 /// operation. We use this primarily for two purposes:
39022 ///
39023 /// 1) Collapse generic shuffles to specialized single instructions when
39024 ///    equivalent. In most cases, this is just an encoding size win, but
39025 ///    sometimes we will collapse multiple generic shuffles into a single
39026 ///    special-purpose shuffle.
39027 /// 2) Look for sequences of shuffle instructions with 3 or more total
39028 ///    instructions, and replace them with the slightly more expensive SSSE3
39029 ///    PSHUFB instruction if available. We do this as the last combining step
39030 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
39031 ///    a suitable short sequence of other instructions. The PSHUFB will either
39032 ///    use a register or have to read from memory and so is slightly (but only
39033 ///    slightly) more expensive than the other shuffle instructions.
39034 ///
39035 /// Because this is inherently a quadratic operation (for each shuffle in
39036 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
39037 /// This should never be an issue in practice as the shuffle lowering doesn't
39038 /// produce sequences of more than 8 instructions.
39039 ///
39040 /// FIXME: We will currently miss some cases where the redundant shuffling
39041 /// would simplify under the threshold for PSHUFB formation because of
39042 /// combine-ordering. To fix this, we should do the redundant instruction
39043 /// combining in this recursive walk.
39044 static SDValue combineX86ShufflesRecursively(
39045     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
39046     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
39047     unsigned MaxDepth, bool HasVariableMask, bool AllowVariableCrossLaneMask,
39048     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
39049     const X86Subtarget &Subtarget) {
39050   assert(RootMask.size() > 0 &&
39051          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
39052          "Illegal shuffle root mask");
39053   MVT RootVT = Root.getSimpleValueType();
39054   assert(RootVT.isVector() && "Shuffles operate on vector types!");
39055   unsigned RootSizeInBits = RootVT.getSizeInBits();
39056 
39057   // Bound the depth of our recursive combine because this is ultimately
39058   // quadratic in nature.
39059   if (Depth >= MaxDepth)
39060     return SDValue();
39061 
39062   // Directly rip through bitcasts to find the underlying operand.
39063   SDValue Op = SrcOps[SrcOpIndex];
39064   Op = peekThroughOneUseBitcasts(Op);
39065 
39066   EVT VT = Op.getValueType();
39067   if (!VT.isVector() || !VT.isSimple())
39068     return SDValue(); // Bail if we hit a non-simple non-vector.
39069 
39070   // FIXME: Just bail on f16 for now.
39071   if (VT.getVectorElementType() == MVT::f16)
39072     return SDValue();
39073 
39074   assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&
39075          "Can only combine shuffles upto size of the root op.");
39076 
39077   // Extract target shuffle mask and resolve sentinels and inputs.
39078   // TODO - determine Op's demanded elts from RootMask.
39079   SmallVector<int, 64> OpMask;
39080   SmallVector<SDValue, 2> OpInputs;
39081   APInt OpUndef, OpZero;
39082   APInt OpDemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
39083   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
39084   if (getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
39085                              OpZero, DAG, Depth, false)) {
39086     // Shuffle inputs must not be larger than the shuffle result.
39087     // TODO: Relax this for single input faux shuffles (e.g. trunc).
39088     if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
39089           return OpInput.getValueSizeInBits() > VT.getSizeInBits();
39090         }))
39091       return SDValue();
39092   } else if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
39093              (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
39094              !isNullConstant(Op.getOperand(1))) {
39095     SDValue SrcVec = Op.getOperand(0);
39096     int ExtractIdx = Op.getConstantOperandVal(1);
39097     unsigned NumElts = VT.getVectorNumElements();
39098     OpInputs.assign({SrcVec});
39099     OpMask.assign(NumElts, SM_SentinelUndef);
39100     std::iota(OpMask.begin(), OpMask.end(), ExtractIdx);
39101     OpZero = OpUndef = APInt::getNullValue(NumElts);
39102   } else {
39103     return SDValue();
39104   }
39105 
39106   // If the shuffle result was smaller than the root, we need to adjust the
39107   // mask indices and pad the mask with undefs.
39108   if (RootSizeInBits > VT.getSizeInBits()) {
39109     unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
39110     unsigned OpMaskSize = OpMask.size();
39111     if (OpInputs.size() > 1) {
39112       unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
39113       for (int &M : OpMask) {
39114         if (M < 0)
39115           continue;
39116         int EltIdx = M % OpMaskSize;
39117         int OpIdx = M / OpMaskSize;
39118         M = (PaddedMaskSize * OpIdx) + EltIdx;
39119       }
39120     }
39121     OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
39122     OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
39123     OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
39124   }
39125 
39126   SmallVector<int, 64> Mask;
39127   SmallVector<SDValue, 16> Ops;
39128 
39129   // We don't need to merge masks if the root is empty.
39130   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
39131   if (EmptyRoot) {
39132     // Only resolve zeros if it will remove an input, otherwise we might end
39133     // up in an infinite loop.
39134     bool ResolveKnownZeros = true;
39135     if (!OpZero.isZero()) {
39136       APInt UsedInputs = APInt::getZero(OpInputs.size());
39137       for (int i = 0, e = OpMask.size(); i != e; ++i) {
39138         int M = OpMask[i];
39139         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
39140           continue;
39141         UsedInputs.setBit(M / OpMask.size());
39142         if (UsedInputs.isAllOnes()) {
39143           ResolveKnownZeros = false;
39144           break;
39145         }
39146       }
39147     }
39148     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
39149                                       ResolveKnownZeros);
39150 
39151     Mask = OpMask;
39152     Ops.append(OpInputs.begin(), OpInputs.end());
39153   } else {
39154     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
39155 
39156     // Add the inputs to the Ops list, avoiding duplicates.
39157     Ops.append(SrcOps.begin(), SrcOps.end());
39158 
39159     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
39160       // Attempt to find an existing match.
39161       SDValue InputBC = peekThroughBitcasts(Input);
39162       for (int i = 0, e = Ops.size(); i < e; ++i)
39163         if (InputBC == peekThroughBitcasts(Ops[i]))
39164           return i;
39165       // Match failed - should we replace an existing Op?
39166       if (InsertionPoint >= 0) {
39167         Ops[InsertionPoint] = Input;
39168         return InsertionPoint;
39169       }
39170       // Add to the end of the Ops list.
39171       Ops.push_back(Input);
39172       return Ops.size() - 1;
39173     };
39174 
39175     SmallVector<int, 2> OpInputIdx;
39176     for (SDValue OpInput : OpInputs)
39177       OpInputIdx.push_back(
39178           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
39179 
39180     assert(((RootMask.size() > OpMask.size() &&
39181              RootMask.size() % OpMask.size() == 0) ||
39182             (OpMask.size() > RootMask.size() &&
39183              OpMask.size() % RootMask.size() == 0) ||
39184             OpMask.size() == RootMask.size()) &&
39185            "The smaller number of elements must divide the larger.");
39186 
39187     // This function can be performance-critical, so we rely on the power-of-2
39188     // knowledge that we have about the mask sizes to replace div/rem ops with
39189     // bit-masks and shifts.
39190     assert(isPowerOf2_32(RootMask.size()) &&
39191            "Non-power-of-2 shuffle mask sizes");
39192     assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes");
39193     unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
39194     unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
39195 
39196     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
39197     unsigned RootRatio =
39198         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
39199     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
39200     assert((RootRatio == 1 || OpRatio == 1) &&
39201            "Must not have a ratio for both incoming and op masks!");
39202 
39203     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
39204     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
39205     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
39206     unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
39207     unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
39208 
39209     Mask.resize(MaskWidth, SM_SentinelUndef);
39210 
39211     // Merge this shuffle operation's mask into our accumulated mask. Note that
39212     // this shuffle's mask will be the first applied to the input, followed by
39213     // the root mask to get us all the way to the root value arrangement. The
39214     // reason for this order is that we are recursing up the operation chain.
39215     for (unsigned i = 0; i < MaskWidth; ++i) {
39216       unsigned RootIdx = i >> RootRatioLog2;
39217       if (RootMask[RootIdx] < 0) {
39218         // This is a zero or undef lane, we're done.
39219         Mask[i] = RootMask[RootIdx];
39220         continue;
39221       }
39222 
39223       unsigned RootMaskedIdx =
39224           RootRatio == 1
39225               ? RootMask[RootIdx]
39226               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
39227 
39228       // Just insert the scaled root mask value if it references an input other
39229       // than the SrcOp we're currently inserting.
39230       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
39231           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
39232         Mask[i] = RootMaskedIdx;
39233         continue;
39234       }
39235 
39236       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
39237       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
39238       if (OpMask[OpIdx] < 0) {
39239         // The incoming lanes are zero or undef, it doesn't matter which ones we
39240         // are using.
39241         Mask[i] = OpMask[OpIdx];
39242         continue;
39243       }
39244 
39245       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
39246       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
39247                                           : (OpMask[OpIdx] << OpRatioLog2) +
39248                                                 (RootMaskedIdx & (OpRatio - 1));
39249 
39250       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
39251       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
39252       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
39253       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
39254 
39255       Mask[i] = OpMaskedIdx;
39256     }
39257   }
39258 
39259   // Remove unused/repeated shuffle source ops.
39260   resolveTargetShuffleInputsAndMask(Ops, Mask);
39261 
39262   // Handle the all undef/zero/ones cases early.
39263   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
39264     return DAG.getUNDEF(RootVT);
39265   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
39266     return getZeroVector(RootVT, Subtarget, DAG, SDLoc(Root));
39267   if (Ops.size() == 1 && ISD::isBuildVectorAllOnes(Ops[0].getNode()) &&
39268       none_of(Mask, [](int M) { return M == SM_SentinelZero; }))
39269     return getOnesVector(RootVT, DAG, SDLoc(Root));
39270 
39271   assert(!Ops.empty() && "Shuffle with no inputs detected");
39272   HasVariableMask |= IsOpVariableMask;
39273 
39274   // Update the list of shuffle nodes that have been combined so far.
39275   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
39276                                                 SrcNodes.end());
39277   CombinedNodes.push_back(Op.getNode());
39278 
39279   // See if we can recurse into each shuffle source op (if it's a target
39280   // shuffle). The source op should only be generally combined if it either has
39281   // a single use (i.e. current Op) or all its users have already been combined,
39282   // if not then we can still combine but should prevent generation of variable
39283   // shuffles to avoid constant pool bloat.
39284   // Don't recurse if we already have more source ops than we can combine in
39285   // the remaining recursion depth.
39286   if (Ops.size() < (MaxDepth - Depth)) {
39287     for (int i = 0, e = Ops.size(); i < e; ++i) {
39288       // For empty roots, we need to resolve zeroable elements before combining
39289       // them with other shuffles.
39290       SmallVector<int, 64> ResolvedMask = Mask;
39291       if (EmptyRoot)
39292         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
39293       bool AllowCrossLaneVar = false;
39294       bool AllowPerLaneVar = false;
39295       if (Ops[i].getNode()->hasOneUse() ||
39296           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode())) {
39297         AllowCrossLaneVar = AllowVariableCrossLaneMask;
39298         AllowPerLaneVar = AllowVariablePerLaneMask;
39299       }
39300       if (SDValue Res = combineX86ShufflesRecursively(
39301               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
39302               HasVariableMask, AllowCrossLaneVar, AllowPerLaneVar, DAG,
39303               Subtarget))
39304         return Res;
39305     }
39306   }
39307 
39308   // Attempt to constant fold all of the constant source ops.
39309   if (SDValue Cst = combineX86ShufflesConstants(
39310           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
39311     return Cst;
39312 
39313   // If constant fold failed and we only have constants - then we have
39314   // multiple uses by a single non-variable shuffle - just bail.
39315   if (Depth == 0 && llvm::all_of(Ops, [&](SDValue Op) {
39316         APInt UndefElts;
39317         SmallVector<APInt> RawBits;
39318         unsigned EltSizeInBits = RootSizeInBits / Mask.size();
39319         return getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
39320                                              RawBits);
39321       })) {
39322     return SDValue();
39323   }
39324 
39325   // Canonicalize the combined shuffle mask chain with horizontal ops.
39326   // NOTE: This will update the Ops and Mask.
39327   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
39328           Ops, Mask, RootSizeInBits, SDLoc(Root), DAG, Subtarget))
39329     return DAG.getBitcast(RootVT, HOp);
39330 
39331   // Try to refine our inputs given our knowledge of target shuffle mask.
39332   for (auto I : enumerate(Ops)) {
39333     int OpIdx = I.index();
39334     SDValue &Op = I.value();
39335 
39336     // What range of shuffle mask element values results in picking from Op?
39337     int Lo = OpIdx * Mask.size();
39338     int Hi = Lo + Mask.size();
39339 
39340     // Which elements of Op do we demand, given the mask's granularity?
39341     APInt OpDemandedElts(Mask.size(), 0);
39342     for (int MaskElt : Mask) {
39343       if (isInRange(MaskElt, Lo, Hi)) { // Picks from Op?
39344         int OpEltIdx = MaskElt - Lo;
39345         OpDemandedElts.setBit(OpEltIdx);
39346       }
39347     }
39348 
39349     // Is the shuffle result smaller than the root?
39350     if (Op.getValueSizeInBits() < RootSizeInBits) {
39351       // We padded the mask with undefs. But we now need to undo that.
39352       unsigned NumExpectedVectorElts = Mask.size();
39353       unsigned EltSizeInBits = RootSizeInBits / NumExpectedVectorElts;
39354       unsigned NumOpVectorElts = Op.getValueSizeInBits() / EltSizeInBits;
39355       assert(!OpDemandedElts.extractBits(
39356                  NumExpectedVectorElts - NumOpVectorElts, NumOpVectorElts) &&
39357              "Demanding the virtual undef widening padding?");
39358       OpDemandedElts = OpDemandedElts.trunc(NumOpVectorElts); // NUW
39359     }
39360 
39361     // The Op itself may be of different VT, so we need to scale the mask.
39362     unsigned NumOpElts = Op.getValueType().getVectorNumElements();
39363     APInt OpScaledDemandedElts = APIntOps::ScaleBitMask(OpDemandedElts, NumOpElts);
39364 
39365     // Can this operand be simplified any further, given it's demanded elements?
39366     if (SDValue NewOp =
39367             DAG.getTargetLoweringInfo().SimplifyMultipleUseDemandedVectorElts(
39368                 Op, OpScaledDemandedElts, DAG))
39369       Op = NewOp;
39370   }
39371   // FIXME: should we rerun resolveTargetShuffleInputsAndMask() now?
39372 
39373   // Widen any subvector shuffle inputs we've collected.
39374   // TODO: Remove this to avoid generating temporary nodes, we should only
39375   // widen once combineX86ShuffleChain has found a match.
39376   if (any_of(Ops, [RootSizeInBits](SDValue Op) {
39377         return Op.getValueSizeInBits() < RootSizeInBits;
39378       })) {
39379     for (SDValue &Op : Ops)
39380       if (Op.getValueSizeInBits() < RootSizeInBits)
39381         Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
39382                             RootSizeInBits);
39383     // Reresolve - we might have repeated subvector sources.
39384     resolveTargetShuffleInputsAndMask(Ops, Mask);
39385   }
39386 
39387   // We can only combine unary and binary shuffle mask cases.
39388   if (Ops.size() <= 2) {
39389     // Minor canonicalization of the accumulated shuffle mask to make it easier
39390     // to match below. All this does is detect masks with sequential pairs of
39391     // elements, and shrink them to the half-width mask. It does this in a loop
39392     // so it will reduce the size of the mask to the minimal width mask which
39393     // performs an equivalent shuffle.
39394     while (Mask.size() > 1) {
39395       SmallVector<int, 64> WidenedMask;
39396       if (!canWidenShuffleElements(Mask, WidenedMask))
39397         break;
39398       Mask = std::move(WidenedMask);
39399     }
39400 
39401     // Canonicalization of binary shuffle masks to improve pattern matching by
39402     // commuting the inputs.
39403     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
39404       ShuffleVectorSDNode::commuteMask(Mask);
39405       std::swap(Ops[0], Ops[1]);
39406     }
39407 
39408     // Finally, try to combine into a single shuffle instruction.
39409     return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
39410                                   AllowVariableCrossLaneMask,
39411                                   AllowVariablePerLaneMask, DAG, Subtarget);
39412   }
39413 
39414   // If that failed and any input is extracted then try to combine as a
39415   // shuffle with the larger type.
39416   return combineX86ShuffleChainWithExtract(
39417       Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
39418       AllowVariablePerLaneMask, DAG, Subtarget);
39419 }
39420 
39421 /// Helper entry wrapper to combineX86ShufflesRecursively.
39422 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
39423                                              const X86Subtarget &Subtarget) {
39424   return combineX86ShufflesRecursively(
39425       {Op}, 0, Op, {0}, {}, /*Depth*/ 0, X86::MaxShuffleCombineDepth,
39426       /*HasVarMask*/ false,
39427       /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, DAG,
39428       Subtarget);
39429 }
39430 
39431 /// Get the PSHUF-style mask from PSHUF node.
39432 ///
39433 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
39434 /// PSHUF-style masks that can be reused with such instructions.
39435 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
39436   MVT VT = N.getSimpleValueType();
39437   SmallVector<int, 4> Mask;
39438   SmallVector<SDValue, 2> Ops;
39439   bool HaveMask =
39440       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask);
39441   (void)HaveMask;
39442   assert(HaveMask);
39443 
39444   // If we have more than 128-bits, only the low 128-bits of shuffle mask
39445   // matter. Check that the upper masks are repeats and remove them.
39446   if (VT.getSizeInBits() > 128) {
39447     int LaneElts = 128 / VT.getScalarSizeInBits();
39448 #ifndef NDEBUG
39449     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
39450       for (int j = 0; j < LaneElts; ++j)
39451         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
39452                "Mask doesn't repeat in high 128-bit lanes!");
39453 #endif
39454     Mask.resize(LaneElts);
39455   }
39456 
39457   switch (N.getOpcode()) {
39458   case X86ISD::PSHUFD:
39459     return Mask;
39460   case X86ISD::PSHUFLW:
39461     Mask.resize(4);
39462     return Mask;
39463   case X86ISD::PSHUFHW:
39464     Mask.erase(Mask.begin(), Mask.begin() + 4);
39465     for (int &M : Mask)
39466       M -= 4;
39467     return Mask;
39468   default:
39469     llvm_unreachable("No valid shuffle instruction found!");
39470   }
39471 }
39472 
39473 /// Search for a combinable shuffle across a chain ending in pshufd.
39474 ///
39475 /// We walk up the chain and look for a combinable shuffle, skipping over
39476 /// shuffles that we could hoist this shuffle's transformation past without
39477 /// altering anything.
39478 static SDValue
39479 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
39480                              SelectionDAG &DAG) {
39481   assert(N.getOpcode() == X86ISD::PSHUFD &&
39482          "Called with something other than an x86 128-bit half shuffle!");
39483   SDLoc DL(N);
39484 
39485   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
39486   // of the shuffles in the chain so that we can form a fresh chain to replace
39487   // this one.
39488   SmallVector<SDValue, 8> Chain;
39489   SDValue V = N.getOperand(0);
39490   for (; V.hasOneUse(); V = V.getOperand(0)) {
39491     switch (V.getOpcode()) {
39492     default:
39493       return SDValue(); // Nothing combined!
39494 
39495     case ISD::BITCAST:
39496       // Skip bitcasts as we always know the type for the target specific
39497       // instructions.
39498       continue;
39499 
39500     case X86ISD::PSHUFD:
39501       // Found another dword shuffle.
39502       break;
39503 
39504     case X86ISD::PSHUFLW:
39505       // Check that the low words (being shuffled) are the identity in the
39506       // dword shuffle, and the high words are self-contained.
39507       if (Mask[0] != 0 || Mask[1] != 1 ||
39508           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
39509         return SDValue();
39510 
39511       Chain.push_back(V);
39512       continue;
39513 
39514     case X86ISD::PSHUFHW:
39515       // Check that the high words (being shuffled) are the identity in the
39516       // dword shuffle, and the low words are self-contained.
39517       if (Mask[2] != 2 || Mask[3] != 3 ||
39518           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
39519         return SDValue();
39520 
39521       Chain.push_back(V);
39522       continue;
39523 
39524     case X86ISD::UNPCKL:
39525     case X86ISD::UNPCKH:
39526       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
39527       // shuffle into a preceding word shuffle.
39528       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
39529           V.getSimpleValueType().getVectorElementType() != MVT::i16)
39530         return SDValue();
39531 
39532       // Search for a half-shuffle which we can combine with.
39533       unsigned CombineOp =
39534           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
39535       if (V.getOperand(0) != V.getOperand(1) ||
39536           !V->isOnlyUserOf(V.getOperand(0).getNode()))
39537         return SDValue();
39538       Chain.push_back(V);
39539       V = V.getOperand(0);
39540       do {
39541         switch (V.getOpcode()) {
39542         default:
39543           return SDValue(); // Nothing to combine.
39544 
39545         case X86ISD::PSHUFLW:
39546         case X86ISD::PSHUFHW:
39547           if (V.getOpcode() == CombineOp)
39548             break;
39549 
39550           Chain.push_back(V);
39551 
39552           LLVM_FALLTHROUGH;
39553         case ISD::BITCAST:
39554           V = V.getOperand(0);
39555           continue;
39556         }
39557         break;
39558       } while (V.hasOneUse());
39559       break;
39560     }
39561     // Break out of the loop if we break out of the switch.
39562     break;
39563   }
39564 
39565   if (!V.hasOneUse())
39566     // We fell out of the loop without finding a viable combining instruction.
39567     return SDValue();
39568 
39569   // Merge this node's mask and our incoming mask.
39570   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
39571   for (int &M : Mask)
39572     M = VMask[M];
39573   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
39574                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
39575 
39576   // Rebuild the chain around this new shuffle.
39577   while (!Chain.empty()) {
39578     SDValue W = Chain.pop_back_val();
39579 
39580     if (V.getValueType() != W.getOperand(0).getValueType())
39581       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
39582 
39583     switch (W.getOpcode()) {
39584     default:
39585       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
39586 
39587     case X86ISD::UNPCKL:
39588     case X86ISD::UNPCKH:
39589       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
39590       break;
39591 
39592     case X86ISD::PSHUFD:
39593     case X86ISD::PSHUFLW:
39594     case X86ISD::PSHUFHW:
39595       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
39596       break;
39597     }
39598   }
39599   if (V.getValueType() != N.getValueType())
39600     V = DAG.getBitcast(N.getValueType(), V);
39601 
39602   // Return the new chain to replace N.
39603   return V;
39604 }
39605 
39606 // Attempt to commute shufps LHS loads:
39607 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
39608 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
39609                                       SelectionDAG &DAG) {
39610   // TODO: Add vXf64 support.
39611   if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
39612     return SDValue();
39613 
39614   // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
39615   auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
39616     if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
39617       return SDValue();
39618     SDValue N0 = V.getOperand(0);
39619     SDValue N1 = V.getOperand(1);
39620     unsigned Imm = V.getConstantOperandVal(2);
39621     const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
39622     if (!X86::mayFoldLoad(peekThroughOneUseBitcasts(N0), Subtarget) ||
39623         X86::mayFoldLoad(peekThroughOneUseBitcasts(N1), Subtarget))
39624       return SDValue();
39625     Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
39626     return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
39627                        DAG.getTargetConstant(Imm, DL, MVT::i8));
39628   };
39629 
39630   switch (N.getOpcode()) {
39631   case X86ISD::VPERMILPI:
39632     if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
39633       unsigned Imm = N.getConstantOperandVal(1);
39634       return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
39635                          DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
39636     }
39637     break;
39638   case X86ISD::SHUFP: {
39639     SDValue N0 = N.getOperand(0);
39640     SDValue N1 = N.getOperand(1);
39641     unsigned Imm = N.getConstantOperandVal(2);
39642     if (N0 == N1) {
39643       if (SDValue NewSHUFP = commuteSHUFP(N, N0))
39644         return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
39645                            DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
39646     } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
39647       return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
39648                          DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
39649     } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
39650       return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
39651                          DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
39652     }
39653     break;
39654   }
39655   }
39656 
39657   return SDValue();
39658 }
39659 
39660 // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
39661 static SDValue canonicalizeShuffleWithBinOps(SDValue N, SelectionDAG &DAG,
39662                                              const SDLoc &DL) {
39663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39664   EVT ShuffleVT = N.getValueType();
39665 
39666   auto IsMergeableWithShuffle = [&DAG](SDValue Op, bool FoldLoad = false) {
39667     // AllZeros/AllOnes constants are freely shuffled and will peek through
39668     // bitcasts. Other constant build vectors do not peek through bitcasts. Only
39669     // merge with target shuffles if it has one use so shuffle combining is
39670     // likely to kick in. Shuffles of splats are expected to be removed.
39671     return ISD::isBuildVectorAllOnes(Op.getNode()) ||
39672            ISD::isBuildVectorAllZeros(Op.getNode()) ||
39673            ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
39674            ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()) ||
39675            (isTargetShuffle(Op.getOpcode()) && Op->hasOneUse()) ||
39676            (FoldLoad && isShuffleFoldableLoad(Op)) ||
39677            DAG.isSplatValue(Op, /*AllowUndefs*/ false);
39678   };
39679   auto IsSafeToMoveShuffle = [ShuffleVT](SDValue Op, unsigned BinOp) {
39680     // Ensure we only shuffle whole vector src elements, unless its a logical
39681     // binops where we can more aggressively move shuffles from dst to src.
39682     return BinOp == ISD::AND || BinOp == ISD::OR || BinOp == ISD::XOR ||
39683            BinOp == X86ISD::ANDNP ||
39684            (Op.getScalarValueSizeInBits() <= ShuffleVT.getScalarSizeInBits());
39685   };
39686 
39687   unsigned Opc = N.getOpcode();
39688   switch (Opc) {
39689   // Unary and Unary+Permute Shuffles.
39690   case X86ISD::PSHUFB: {
39691     // Don't merge PSHUFB if it contains zero'd elements.
39692     SmallVector<int> Mask;
39693     SmallVector<SDValue> Ops;
39694     if (!getTargetShuffleMask(N.getNode(), ShuffleVT.getSimpleVT(), false, Ops,
39695                               Mask))
39696       break;
39697     LLVM_FALLTHROUGH;
39698   }
39699   case X86ISD::VBROADCAST:
39700   case X86ISD::MOVDDUP:
39701   case X86ISD::PSHUFD:
39702   case X86ISD::PSHUFHW:
39703   case X86ISD::PSHUFLW:
39704   case X86ISD::VPERMI:
39705   case X86ISD::VPERMILPI: {
39706     if (N.getOperand(0).getValueType() == ShuffleVT &&
39707         N->isOnlyUserOf(N.getOperand(0).getNode())) {
39708       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
39709       unsigned SrcOpcode = N0.getOpcode();
39710       if (TLI.isBinOp(SrcOpcode) && IsSafeToMoveShuffle(N0, SrcOpcode)) {
39711         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
39712         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
39713         if (IsMergeableWithShuffle(Op00, Opc != X86ISD::PSHUFB) ||
39714             IsMergeableWithShuffle(Op01, Opc != X86ISD::PSHUFB)) {
39715           SDValue LHS, RHS;
39716           Op00 = DAG.getBitcast(ShuffleVT, Op00);
39717           Op01 = DAG.getBitcast(ShuffleVT, Op01);
39718           if (N.getNumOperands() == 2) {
39719             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, N.getOperand(1));
39720             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, N.getOperand(1));
39721           } else {
39722             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00);
39723             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01);
39724           }
39725           EVT OpVT = N0.getValueType();
39726           return DAG.getBitcast(ShuffleVT,
39727                                 DAG.getNode(SrcOpcode, DL, OpVT,
39728                                             DAG.getBitcast(OpVT, LHS),
39729                                             DAG.getBitcast(OpVT, RHS)));
39730         }
39731       }
39732     }
39733     break;
39734   }
39735   // Binary and Binary+Permute Shuffles.
39736   case X86ISD::INSERTPS: {
39737     // Don't merge INSERTPS if it contains zero'd elements.
39738     unsigned InsertPSMask = N.getConstantOperandVal(2);
39739     unsigned ZeroMask = InsertPSMask & 0xF;
39740     if (ZeroMask != 0)
39741       break;
39742     LLVM_FALLTHROUGH;
39743   }
39744   case X86ISD::MOVSD:
39745   case X86ISD::MOVSS:
39746   case X86ISD::BLENDI:
39747   case X86ISD::SHUFP:
39748   case X86ISD::UNPCKH:
39749   case X86ISD::UNPCKL: {
39750     if (N->isOnlyUserOf(N.getOperand(0).getNode()) &&
39751         N->isOnlyUserOf(N.getOperand(1).getNode())) {
39752       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
39753       SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
39754       unsigned SrcOpcode = N0.getOpcode();
39755       if (TLI.isBinOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
39756           IsSafeToMoveShuffle(N0, SrcOpcode) &&
39757           IsSafeToMoveShuffle(N1, SrcOpcode)) {
39758         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
39759         SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
39760         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
39761         SDValue Op11 = peekThroughOneUseBitcasts(N1.getOperand(1));
39762         // Ensure the total number of shuffles doesn't increase by folding this
39763         // shuffle through to the source ops.
39764         if (((IsMergeableWithShuffle(Op00) && IsMergeableWithShuffle(Op10)) ||
39765              (IsMergeableWithShuffle(Op01) && IsMergeableWithShuffle(Op11))) ||
39766             ((IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op10)) &&
39767              (IsMergeableWithShuffle(Op01) || IsMergeableWithShuffle(Op11)))) {
39768           SDValue LHS, RHS;
39769           Op00 = DAG.getBitcast(ShuffleVT, Op00);
39770           Op10 = DAG.getBitcast(ShuffleVT, Op10);
39771           Op01 = DAG.getBitcast(ShuffleVT, Op01);
39772           Op11 = DAG.getBitcast(ShuffleVT, Op11);
39773           if (N.getNumOperands() == 3) {
39774             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
39775             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11, N.getOperand(2));
39776           } else {
39777             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
39778             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11);
39779           }
39780           EVT OpVT = N0.getValueType();
39781           return DAG.getBitcast(ShuffleVT,
39782                                 DAG.getNode(SrcOpcode, DL, OpVT,
39783                                             DAG.getBitcast(OpVT, LHS),
39784                                             DAG.getBitcast(OpVT, RHS)));
39785         }
39786       }
39787     }
39788     break;
39789   }
39790   }
39791   return SDValue();
39792 }
39793 
39794 /// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
39795 static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
39796                                                       SelectionDAG &DAG,
39797                                                       const SDLoc &DL) {
39798   assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle");
39799 
39800   MVT VT = V.getSimpleValueType();
39801   SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
39802   SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
39803   unsigned SrcOpc0 = Src0.getOpcode();
39804   unsigned SrcOpc1 = Src1.getOpcode();
39805   EVT SrcVT0 = Src0.getValueType();
39806   EVT SrcVT1 = Src1.getValueType();
39807 
39808   if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
39809     return SDValue();
39810 
39811   switch (SrcOpc0) {
39812   case X86ISD::MOVDDUP: {
39813     SDValue LHS = Src0.getOperand(0);
39814     SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
39815     SDValue Res =
39816         DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS, V.getOperand(2));
39817     Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res);
39818     return DAG.getBitcast(VT, Res);
39819   }
39820   case X86ISD::VPERMILPI:
39821     // TODO: Handle v4f64 permutes with different low/high lane masks.
39822     if (SrcVT0 == MVT::v4f64) {
39823       uint64_t Mask = Src0.getConstantOperandVal(1);
39824       if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
39825         break;
39826     }
39827     LLVM_FALLTHROUGH;
39828   case X86ISD::VSHLI:
39829   case X86ISD::VSRLI:
39830   case X86ISD::VSRAI:
39831   case X86ISD::PSHUFD:
39832     if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
39833       SDValue LHS = Src0.getOperand(0);
39834       SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
39835       SDValue Res = DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS,
39836                                 V.getOperand(2));
39837       Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res, Src0.getOperand(1));
39838       return DAG.getBitcast(VT, Res);
39839     }
39840     break;
39841   }
39842 
39843   return SDValue();
39844 }
39845 
39846 /// Try to combine x86 target specific shuffles.
39847 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
39848                                     TargetLowering::DAGCombinerInfo &DCI,
39849                                     const X86Subtarget &Subtarget) {
39850   SDLoc DL(N);
39851   MVT VT = N.getSimpleValueType();
39852   SmallVector<int, 4> Mask;
39853   unsigned Opcode = N.getOpcode();
39854 
39855   if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
39856     return R;
39857 
39858   // Handle specific target shuffles.
39859   switch (Opcode) {
39860   case X86ISD::MOVDDUP: {
39861     SDValue Src = N.getOperand(0);
39862     // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
39863     if (VT == MVT::v2f64 && Src.hasOneUse() &&
39864         ISD::isNormalLoad(Src.getNode())) {
39865       LoadSDNode *LN = cast<LoadSDNode>(Src);
39866       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
39867         SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
39868         DCI.CombineTo(N.getNode(), Movddup);
39869         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
39870         DCI.recursivelyDeleteUnusedNodes(LN);
39871         return N; // Return N so it doesn't get rechecked!
39872       }
39873     }
39874 
39875     return SDValue();
39876   }
39877   case X86ISD::VBROADCAST: {
39878     SDValue Src = N.getOperand(0);
39879     SDValue BC = peekThroughBitcasts(Src);
39880     EVT SrcVT = Src.getValueType();
39881     EVT BCVT = BC.getValueType();
39882 
39883     // If broadcasting from another shuffle, attempt to simplify it.
39884     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
39885     if (isTargetShuffle(BC.getOpcode()) &&
39886         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
39887       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
39888       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
39889                                         SM_SentinelUndef);
39890       for (unsigned i = 0; i != Scale; ++i)
39891         DemandedMask[i] = i;
39892       if (SDValue Res = combineX86ShufflesRecursively(
39893               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
39894               X86::MaxShuffleCombineDepth,
39895               /*HasVarMask*/ false, /*AllowCrossLaneVarMask*/ true,
39896               /*AllowPerLaneVarMask*/ true, DAG, Subtarget))
39897         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
39898                            DAG.getBitcast(SrcVT, Res));
39899     }
39900 
39901     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
39902     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
39903     if (Src.getOpcode() == ISD::BITCAST &&
39904         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
39905         DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
39906         FixedVectorType::isValidElementType(
39907             BCVT.getScalarType().getTypeForEVT(*DAG.getContext()))) {
39908       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
39909                                    VT.getVectorNumElements());
39910       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
39911     }
39912 
39913     // Reduce broadcast source vector to lowest 128-bits.
39914     if (SrcVT.getSizeInBits() > 128)
39915       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
39916                          extract128BitVector(Src, 0, DAG, DL));
39917 
39918     // broadcast(scalar_to_vector(x)) -> broadcast(x).
39919     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
39920       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
39921 
39922     // broadcast(extract_vector_elt(x, 0)) -> broadcast(x).
39923     if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
39924         isNullConstant(Src.getOperand(1)) &&
39925         DAG.getTargetLoweringInfo().isTypeLegal(
39926             Src.getOperand(0).getValueType()))
39927       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
39928 
39929     // Share broadcast with the longest vector and extract low subvector (free).
39930     // Ensure the same SDValue from the SDNode use is being used.
39931     for (SDNode *User : Src->uses())
39932       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
39933           Src == User->getOperand(0) &&
39934           User->getValueSizeInBits(0).getFixedSize() >
39935               VT.getFixedSizeInBits()) {
39936         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
39937                                 VT.getSizeInBits());
39938       }
39939 
39940     // vbroadcast(scalarload X) -> vbroadcast_load X
39941     // For float loads, extract other uses of the scalar from the broadcast.
39942     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
39943         ISD::isNormalLoad(Src.getNode())) {
39944       LoadSDNode *LN = cast<LoadSDNode>(Src);
39945       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39946       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39947       SDValue BcastLd =
39948           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
39949                                   LN->getMemoryVT(), LN->getMemOperand());
39950       // If the load value is used only by N, replace it via CombineTo N.
39951       bool NoReplaceExtract = Src.hasOneUse();
39952       DCI.CombineTo(N.getNode(), BcastLd);
39953       if (NoReplaceExtract) {
39954         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39955         DCI.recursivelyDeleteUnusedNodes(LN);
39956       } else {
39957         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
39958                                   DAG.getIntPtrConstant(0, DL));
39959         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
39960       }
39961       return N; // Return N so it doesn't get rechecked!
39962     }
39963 
39964     // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
39965     // i16. So shrink it ourselves if we can make a broadcast_load.
39966     if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
39967         Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
39968       assert(Subtarget.hasAVX2() && "Expected AVX2");
39969       SDValue TruncIn = Src.getOperand(0);
39970 
39971       // If this is a truncate of a non extending load we can just narrow it to
39972       // use a broadcast_load.
39973       if (ISD::isNormalLoad(TruncIn.getNode())) {
39974         LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
39975         // Unless its volatile or atomic.
39976         if (LN->isSimple()) {
39977           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39978           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39979           SDValue BcastLd = DAG.getMemIntrinsicNode(
39980               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
39981               LN->getPointerInfo(), LN->getOriginalAlign(),
39982               LN->getMemOperand()->getFlags());
39983           DCI.CombineTo(N.getNode(), BcastLd);
39984           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39985           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
39986           return N; // Return N so it doesn't get rechecked!
39987         }
39988       }
39989 
39990       // If this is a truncate of an i16 extload, we can directly replace it.
39991       if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
39992           ISD::isEXTLoad(Src.getOperand(0).getNode())) {
39993         LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
39994         if (LN->getMemoryVT().getSizeInBits() == 16) {
39995           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39996           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39997           SDValue BcastLd =
39998               DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
39999                                       LN->getMemoryVT(), LN->getMemOperand());
40000           DCI.CombineTo(N.getNode(), BcastLd);
40001           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40002           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
40003           return N; // Return N so it doesn't get rechecked!
40004         }
40005       }
40006 
40007       // If this is a truncate of load that has been shifted right, we can
40008       // offset the pointer and use a narrower load.
40009       if (TruncIn.getOpcode() == ISD::SRL &&
40010           TruncIn.getOperand(0).hasOneUse() &&
40011           isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
40012           ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
40013         LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
40014         unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
40015         // Make sure the shift amount and the load size are divisible by 16.
40016         // Don't do this if the load is volatile or atomic.
40017         if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
40018             LN->isSimple()) {
40019           unsigned Offset = ShiftAmt / 8;
40020           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40021           SDValue Ptr = DAG.getMemBasePlusOffset(LN->getBasePtr(),
40022                                                  TypeSize::Fixed(Offset), DL);
40023           SDValue Ops[] = { LN->getChain(), Ptr };
40024           SDValue BcastLd = DAG.getMemIntrinsicNode(
40025               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
40026               LN->getPointerInfo().getWithOffset(Offset),
40027               LN->getOriginalAlign(),
40028               LN->getMemOperand()->getFlags());
40029           DCI.CombineTo(N.getNode(), BcastLd);
40030           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40031           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
40032           return N; // Return N so it doesn't get rechecked!
40033         }
40034       }
40035     }
40036 
40037     // vbroadcast(vzload X) -> vbroadcast_load X
40038     if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
40039       MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
40040       if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
40041         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40042         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
40043         SDValue BcastLd =
40044             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
40045                                     LN->getMemoryVT(), LN->getMemOperand());
40046         DCI.CombineTo(N.getNode(), BcastLd);
40047         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40048         DCI.recursivelyDeleteUnusedNodes(LN);
40049         return N; // Return N so it doesn't get rechecked!
40050       }
40051     }
40052 
40053     // vbroadcast(vector load X) -> vbroadcast_load
40054     if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
40055          SrcVT == MVT::v4i32) &&
40056         Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
40057       LoadSDNode *LN = cast<LoadSDNode>(Src);
40058       // Unless the load is volatile or atomic.
40059       if (LN->isSimple()) {
40060         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40061         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
40062         SDValue BcastLd = DAG.getMemIntrinsicNode(
40063             X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
40064             LN->getPointerInfo(), LN->getOriginalAlign(),
40065             LN->getMemOperand()->getFlags());
40066         DCI.CombineTo(N.getNode(), BcastLd);
40067         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40068         DCI.recursivelyDeleteUnusedNodes(LN);
40069         return N; // Return N so it doesn't get rechecked!
40070       }
40071     }
40072 
40073     return SDValue();
40074   }
40075   case X86ISD::VZEXT_MOVL: {
40076     SDValue N0 = N.getOperand(0);
40077 
40078     // If this a vzmovl of a full vector load, replace it with a vzload, unless
40079     // the load is volatile.
40080     if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
40081       auto *LN = cast<LoadSDNode>(N0);
40082       if (SDValue VZLoad =
40083               narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
40084         DCI.CombineTo(N.getNode(), VZLoad);
40085         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
40086         DCI.recursivelyDeleteUnusedNodes(LN);
40087         return N;
40088       }
40089     }
40090 
40091     // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
40092     // and can just use a VZEXT_LOAD.
40093     // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
40094     if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
40095       auto *LN = cast<MemSDNode>(N0);
40096       if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
40097         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40098         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
40099         SDValue VZLoad =
40100             DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
40101                                     LN->getMemoryVT(), LN->getMemOperand());
40102         DCI.CombineTo(N.getNode(), VZLoad);
40103         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
40104         DCI.recursivelyDeleteUnusedNodes(LN);
40105         return N;
40106       }
40107     }
40108 
40109     // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
40110     // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
40111     // if the upper bits of the i64 are zero.
40112     if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
40113         N0.getOperand(0).hasOneUse() &&
40114         N0.getOperand(0).getValueType() == MVT::i64) {
40115       SDValue In = N0.getOperand(0);
40116       APInt Mask = APInt::getHighBitsSet(64, 32);
40117       if (DAG.MaskedValueIsZero(In, Mask)) {
40118         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
40119         MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
40120         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
40121         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
40122         return DAG.getBitcast(VT, Movl);
40123       }
40124     }
40125 
40126     // Load a scalar integer constant directly to XMM instead of transferring an
40127     // immediate value from GPR.
40128     // vzext_movl (scalar_to_vector C) --> load [C,0...]
40129     if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
40130       if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
40131         // Create a vector constant - scalar constant followed by zeros.
40132         EVT ScalarVT = N0.getOperand(0).getValueType();
40133         Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
40134         unsigned NumElts = VT.getVectorNumElements();
40135         Constant *Zero = ConstantInt::getNullValue(ScalarTy);
40136         SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
40137         ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
40138 
40139         // Load the vector constant from constant pool.
40140         MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
40141         SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
40142         MachinePointerInfo MPI =
40143             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
40144         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
40145         return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
40146                            MachineMemOperand::MOLoad);
40147       }
40148     }
40149 
40150     // Pull subvector inserts into undef through VZEXT_MOVL by making it an
40151     // insert into a zero vector. This helps get VZEXT_MOVL closer to
40152     // scalar_to_vectors where 256/512 are canonicalized to an insert and a
40153     // 128-bit scalar_to_vector. This reduces the number of isel patterns.
40154     if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
40155       SDValue V = peekThroughOneUseBitcasts(N0);
40156 
40157       if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
40158           isNullConstant(V.getOperand(2))) {
40159         SDValue In = V.getOperand(1);
40160         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
40161                                      In.getValueSizeInBits() /
40162                                          VT.getScalarSizeInBits());
40163         In = DAG.getBitcast(SubVT, In);
40164         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
40165         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
40166                            getZeroVector(VT, Subtarget, DAG, DL), Movl,
40167                            V.getOperand(2));
40168       }
40169     }
40170 
40171     return SDValue();
40172   }
40173   case X86ISD::BLENDI: {
40174     SDValue N0 = N.getOperand(0);
40175     SDValue N1 = N.getOperand(1);
40176 
40177     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
40178     // TODO: Handle MVT::v16i16 repeated blend mask.
40179     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
40180         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
40181       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
40182       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
40183           SrcVT.getScalarSizeInBits() >= 32) {
40184         unsigned BlendMask = N.getConstantOperandVal(2);
40185         unsigned Size = VT.getVectorNumElements();
40186         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
40187         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
40188         return DAG.getBitcast(
40189             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
40190                             N1.getOperand(0),
40191                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
40192       }
40193     }
40194     return SDValue();
40195   }
40196   case X86ISD::SHUFP: {
40197     // Fold shufps(shuffle(x),shuffle(y)) -> shufps(x,y).
40198     // This is a more relaxed shuffle combiner that can ignore oneuse limits.
40199     // TODO: Support types other than v4f32.
40200     if (VT == MVT::v4f32) {
40201       bool Updated = false;
40202       SmallVector<int> Mask;
40203       SmallVector<SDValue> Ops;
40204       if (getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask) &&
40205           Ops.size() == 2) {
40206         for (int i = 0; i != 2; ++i) {
40207           SmallVector<SDValue> SubOps;
40208           SmallVector<int> SubMask, SubScaledMask;
40209           SDValue Sub = peekThroughBitcasts(Ops[i]);
40210           // TODO: Scaling might be easier if we specify the demanded elts.
40211           if (getTargetShuffleInputs(Sub, SubOps, SubMask, DAG, 0, false) &&
40212               scaleShuffleElements(SubMask, 4, SubScaledMask) &&
40213               SubOps.size() == 1 && isUndefOrInRange(SubScaledMask, 0, 4)) {
40214             int Ofs = i * 2;
40215             Mask[Ofs + 0] = SubScaledMask[Mask[Ofs + 0] % 4] + (i * 4);
40216             Mask[Ofs + 1] = SubScaledMask[Mask[Ofs + 1] % 4] + (i * 4);
40217             Ops[i] = DAG.getBitcast(VT, SubOps[0]);
40218             Updated = true;
40219           }
40220         }
40221       }
40222       if (Updated) {
40223         for (int &M : Mask)
40224           M %= 4;
40225         Ops.push_back(getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
40226         return DAG.getNode(X86ISD::SHUFP, DL, VT, Ops);
40227       }
40228     }
40229     return SDValue();
40230   }
40231   case X86ISD::VPERMI: {
40232     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
40233     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
40234     SDValue N0 = N.getOperand(0);
40235     SDValue N1 = N.getOperand(1);
40236     unsigned EltSizeInBits = VT.getScalarSizeInBits();
40237     if (N0.getOpcode() == ISD::BITCAST &&
40238         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
40239       SDValue Src = N0.getOperand(0);
40240       EVT SrcVT = Src.getValueType();
40241       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
40242       return DAG.getBitcast(VT, Res);
40243     }
40244     return SDValue();
40245   }
40246   case X86ISD::VPERM2X128: {
40247     // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
40248     SDValue LHS = N->getOperand(0);
40249     SDValue RHS = N->getOperand(1);
40250     if (LHS.getOpcode() == ISD::BITCAST &&
40251         (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
40252       EVT SrcVT = LHS.getOperand(0).getValueType();
40253       if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
40254         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
40255                                               DAG.getBitcast(SrcVT, LHS),
40256                                               DAG.getBitcast(SrcVT, RHS),
40257                                               N->getOperand(2)));
40258       }
40259     }
40260 
40261     // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
40262     if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
40263       return Res;
40264 
40265     // Fold vperm2x128 subvector shuffle with an inner concat pattern.
40266     // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
40267     auto FindSubVector128 = [&](unsigned Idx) {
40268       if (Idx > 3)
40269         return SDValue();
40270       SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
40271       SmallVector<SDValue> SubOps;
40272       if (collectConcatOps(Src.getNode(), SubOps, DAG) && SubOps.size() == 2)
40273         return SubOps[Idx & 1];
40274       unsigned NumElts = Src.getValueType().getVectorNumElements();
40275       if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
40276           Src.getOperand(1).getValueSizeInBits() == 128 &&
40277           Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
40278         return Src.getOperand(1);
40279       }
40280       return SDValue();
40281     };
40282     unsigned Imm = N.getConstantOperandVal(2);
40283     if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
40284       if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
40285         MVT SubVT = VT.getHalfNumVectorElementsVT();
40286         SubLo = DAG.getBitcast(SubVT, SubLo);
40287         SubHi = DAG.getBitcast(SubVT, SubHi);
40288         return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
40289       }
40290     }
40291     return SDValue();
40292   }
40293   case X86ISD::PSHUFD:
40294   case X86ISD::PSHUFLW:
40295   case X86ISD::PSHUFHW:
40296     Mask = getPSHUFShuffleMask(N);
40297     assert(Mask.size() == 4);
40298     break;
40299   case X86ISD::MOVSD:
40300   case X86ISD::MOVSH:
40301   case X86ISD::MOVSS: {
40302     SDValue N0 = N.getOperand(0);
40303     SDValue N1 = N.getOperand(1);
40304 
40305     // Canonicalize scalar FPOps:
40306     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
40307     // If commutable, allow OP(N1[0], N0[0]).
40308     unsigned Opcode1 = N1.getOpcode();
40309     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
40310         Opcode1 == ISD::FDIV) {
40311       SDValue N10 = N1.getOperand(0);
40312       SDValue N11 = N1.getOperand(1);
40313       if (N10 == N0 ||
40314           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
40315         if (N10 != N0)
40316           std::swap(N10, N11);
40317         MVT SVT = VT.getVectorElementType();
40318         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
40319         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
40320         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
40321         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
40322         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
40323         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
40324       }
40325     }
40326 
40327     return SDValue();
40328   }
40329   case X86ISD::INSERTPS: {
40330     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
40331     SDValue Op0 = N.getOperand(0);
40332     SDValue Op1 = N.getOperand(1);
40333     unsigned InsertPSMask = N.getConstantOperandVal(2);
40334     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
40335     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
40336     unsigned ZeroMask = InsertPSMask & 0xF;
40337 
40338     // If we zero out all elements from Op0 then we don't need to reference it.
40339     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
40340       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
40341                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40342 
40343     // If we zero out the element from Op1 then we don't need to reference it.
40344     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
40345       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
40346                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40347 
40348     // Attempt to merge insertps Op1 with an inner target shuffle node.
40349     SmallVector<int, 8> TargetMask1;
40350     SmallVector<SDValue, 2> Ops1;
40351     APInt KnownUndef1, KnownZero1;
40352     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
40353                                      KnownZero1)) {
40354       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
40355         // Zero/UNDEF insertion - zero out element and remove dependency.
40356         InsertPSMask |= (1u << DstIdx);
40357         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
40358                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40359       }
40360       // Update insertps mask srcidx and reference the source input directly.
40361       int M = TargetMask1[SrcIdx];
40362       assert(0 <= M && M < 8 && "Shuffle index out of range");
40363       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
40364       Op1 = Ops1[M < 4 ? 0 : 1];
40365       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
40366                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40367     }
40368 
40369     // Attempt to merge insertps Op0 with an inner target shuffle node.
40370     SmallVector<int, 8> TargetMask0;
40371     SmallVector<SDValue, 2> Ops0;
40372     APInt KnownUndef0, KnownZero0;
40373     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
40374                                      KnownZero0)) {
40375       bool Updated = false;
40376       bool UseInput00 = false;
40377       bool UseInput01 = false;
40378       for (int i = 0; i != 4; ++i) {
40379         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
40380           // No change if element is already zero or the inserted element.
40381           continue;
40382         }
40383 
40384         if (KnownUndef0[i] || KnownZero0[i]) {
40385           // If the target mask is undef/zero then we must zero the element.
40386           InsertPSMask |= (1u << i);
40387           Updated = true;
40388           continue;
40389         }
40390 
40391         // The input vector element must be inline.
40392         int M = TargetMask0[i];
40393         if (M != i && M != (i + 4))
40394           return SDValue();
40395 
40396         // Determine which inputs of the target shuffle we're using.
40397         UseInput00 |= (0 <= M && M < 4);
40398         UseInput01 |= (4 <= M);
40399       }
40400 
40401       // If we're not using both inputs of the target shuffle then use the
40402       // referenced input directly.
40403       if (UseInput00 && !UseInput01) {
40404         Updated = true;
40405         Op0 = Ops0[0];
40406       } else if (!UseInput00 && UseInput01) {
40407         Updated = true;
40408         Op0 = Ops0[1];
40409       }
40410 
40411       if (Updated)
40412         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
40413                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40414     }
40415 
40416     // If we're inserting an element from a vbroadcast load, fold the
40417     // load into the X86insertps instruction. We need to convert the scalar
40418     // load to a vector and clear the source lane of the INSERTPS control.
40419     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
40420       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
40421       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
40422         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
40423                                    MemIntr->getBasePtr(),
40424                                    MemIntr->getMemOperand());
40425         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
40426                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
40427                                        Load),
40428                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
40429         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
40430         return Insert;
40431       }
40432     }
40433 
40434     return SDValue();
40435   }
40436   default:
40437     return SDValue();
40438   }
40439 
40440   // Nuke no-op shuffles that show up after combining.
40441   if (isNoopShuffleMask(Mask))
40442     return N.getOperand(0);
40443 
40444   // Look for simplifications involving one or two shuffle instructions.
40445   SDValue V = N.getOperand(0);
40446   switch (N.getOpcode()) {
40447   default:
40448     break;
40449   case X86ISD::PSHUFLW:
40450   case X86ISD::PSHUFHW:
40451     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
40452 
40453     // See if this reduces to a PSHUFD which is no more expensive and can
40454     // combine with more operations. Note that it has to at least flip the
40455     // dwords as otherwise it would have been removed as a no-op.
40456     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
40457       int DMask[] = {0, 1, 2, 3};
40458       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
40459       DMask[DOffset + 0] = DOffset + 1;
40460       DMask[DOffset + 1] = DOffset + 0;
40461       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
40462       V = DAG.getBitcast(DVT, V);
40463       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
40464                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
40465       return DAG.getBitcast(VT, V);
40466     }
40467 
40468     // Look for shuffle patterns which can be implemented as a single unpack.
40469     // FIXME: This doesn't handle the location of the PSHUFD generically, and
40470     // only works when we have a PSHUFD followed by two half-shuffles.
40471     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
40472         (V.getOpcode() == X86ISD::PSHUFLW ||
40473          V.getOpcode() == X86ISD::PSHUFHW) &&
40474         V.getOpcode() != N.getOpcode() &&
40475         V.hasOneUse() && V.getOperand(0).hasOneUse()) {
40476       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
40477       if (D.getOpcode() == X86ISD::PSHUFD) {
40478         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
40479         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
40480         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
40481         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
40482         int WordMask[8];
40483         for (int i = 0; i < 4; ++i) {
40484           WordMask[i + NOffset] = Mask[i] + NOffset;
40485           WordMask[i + VOffset] = VMask[i] + VOffset;
40486         }
40487         // Map the word mask through the DWord mask.
40488         int MappedMask[8];
40489         for (int i = 0; i < 8; ++i)
40490           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
40491         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
40492             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
40493           // We can replace all three shuffles with an unpack.
40494           V = DAG.getBitcast(VT, D.getOperand(0));
40495           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
40496                                                 : X86ISD::UNPCKH,
40497                              DL, VT, V, V);
40498         }
40499       }
40500     }
40501 
40502     break;
40503 
40504   case X86ISD::PSHUFD:
40505     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
40506       return NewN;
40507 
40508     break;
40509   }
40510 
40511   return SDValue();
40512 }
40513 
40514 /// Checks if the shuffle mask takes subsequent elements
40515 /// alternately from two vectors.
40516 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
40517 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
40518 
40519   int ParitySrc[2] = {-1, -1};
40520   unsigned Size = Mask.size();
40521   for (unsigned i = 0; i != Size; ++i) {
40522     int M = Mask[i];
40523     if (M < 0)
40524       continue;
40525 
40526     // Make sure we are using the matching element from the input.
40527     if ((M % Size) != i)
40528       return false;
40529 
40530     // Make sure we use the same input for all elements of the same parity.
40531     int Src = M / Size;
40532     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
40533       return false;
40534     ParitySrc[i % 2] = Src;
40535   }
40536 
40537   // Make sure each input is used.
40538   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
40539     return false;
40540 
40541   Op0Even = ParitySrc[0] == 0;
40542   return true;
40543 }
40544 
40545 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
40546 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
40547 /// are written to the parameters \p Opnd0 and \p Opnd1.
40548 ///
40549 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
40550 /// so it is easier to generically match. We also insert dummy vector shuffle
40551 /// nodes for the operands which explicitly discard the lanes which are unused
40552 /// by this operation to try to flow through the rest of the combiner
40553 /// the fact that they're unused.
40554 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
40555                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
40556                              bool &IsSubAdd) {
40557 
40558   EVT VT = N->getValueType(0);
40559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40560   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
40561       !VT.getSimpleVT().isFloatingPoint())
40562     return false;
40563 
40564   // We only handle target-independent shuffles.
40565   // FIXME: It would be easy and harmless to use the target shuffle mask
40566   // extraction tool to support more.
40567   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
40568     return false;
40569 
40570   SDValue V1 = N->getOperand(0);
40571   SDValue V2 = N->getOperand(1);
40572 
40573   // Make sure we have an FADD and an FSUB.
40574   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
40575       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
40576       V1.getOpcode() == V2.getOpcode())
40577     return false;
40578 
40579   // If there are other uses of these operations we can't fold them.
40580   if (!V1->hasOneUse() || !V2->hasOneUse())
40581     return false;
40582 
40583   // Ensure that both operations have the same operands. Note that we can
40584   // commute the FADD operands.
40585   SDValue LHS, RHS;
40586   if (V1.getOpcode() == ISD::FSUB) {
40587     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
40588     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
40589         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
40590       return false;
40591   } else {
40592     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
40593     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
40594     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
40595         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
40596       return false;
40597   }
40598 
40599   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
40600   bool Op0Even;
40601   if (!isAddSubOrSubAddMask(Mask, Op0Even))
40602     return false;
40603 
40604   // It's a subadd if the vector in the even parity is an FADD.
40605   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
40606                      : V2->getOpcode() == ISD::FADD;
40607 
40608   Opnd0 = LHS;
40609   Opnd1 = RHS;
40610   return true;
40611 }
40612 
40613 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
40614 static SDValue combineShuffleToFMAddSub(SDNode *N,
40615                                         const X86Subtarget &Subtarget,
40616                                         SelectionDAG &DAG) {
40617   // We only handle target-independent shuffles.
40618   // FIXME: It would be easy and harmless to use the target shuffle mask
40619   // extraction tool to support more.
40620   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
40621     return SDValue();
40622 
40623   MVT VT = N->getSimpleValueType(0);
40624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40625   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
40626     return SDValue();
40627 
40628   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
40629   SDValue Op0 = N->getOperand(0);
40630   SDValue Op1 = N->getOperand(1);
40631   SDValue FMAdd = Op0, FMSub = Op1;
40632   if (FMSub.getOpcode() != X86ISD::FMSUB)
40633     std::swap(FMAdd, FMSub);
40634 
40635   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
40636       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
40637       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
40638       FMAdd.getOperand(2) != FMSub.getOperand(2))
40639     return SDValue();
40640 
40641   // Check for correct shuffle mask.
40642   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
40643   bool Op0Even;
40644   if (!isAddSubOrSubAddMask(Mask, Op0Even))
40645     return SDValue();
40646 
40647   // FMAddSub takes zeroth operand from FMSub node.
40648   SDLoc DL(N);
40649   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
40650   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
40651   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
40652                      FMAdd.getOperand(2));
40653 }
40654 
40655 /// Try to combine a shuffle into a target-specific add-sub or
40656 /// mul-add-sub node.
40657 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
40658                                                 const X86Subtarget &Subtarget,
40659                                                 SelectionDAG &DAG) {
40660   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
40661     return V;
40662 
40663   SDValue Opnd0, Opnd1;
40664   bool IsSubAdd;
40665   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
40666     return SDValue();
40667 
40668   MVT VT = N->getSimpleValueType(0);
40669   SDLoc DL(N);
40670 
40671   // Try to generate X86ISD::FMADDSUB node here.
40672   SDValue Opnd2;
40673   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
40674     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
40675     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
40676   }
40677 
40678   if (IsSubAdd)
40679     return SDValue();
40680 
40681   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
40682   // the ADDSUB idiom has been successfully recognized. There are no known
40683   // X86 targets with 512-bit ADDSUB instructions!
40684   if (VT.is512BitVector())
40685     return SDValue();
40686 
40687   // Do not generate X86ISD::ADDSUB node for FP16's vector types even though
40688   // the ADDSUB idiom has been successfully recognized. There are no known
40689   // X86 targets with FP16 ADDSUB instructions!
40690   if (VT.getVectorElementType() == MVT::f16)
40691     return SDValue();
40692 
40693   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
40694 }
40695 
40696 // We are looking for a shuffle where both sources are concatenated with undef
40697 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
40698 // if we can express this as a single-source shuffle, that's preferable.
40699 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
40700                                            const X86Subtarget &Subtarget) {
40701   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
40702     return SDValue();
40703 
40704   EVT VT = N->getValueType(0);
40705 
40706   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
40707   if (!VT.is128BitVector() && !VT.is256BitVector())
40708     return SDValue();
40709 
40710   if (VT.getVectorElementType() != MVT::i32 &&
40711       VT.getVectorElementType() != MVT::i64 &&
40712       VT.getVectorElementType() != MVT::f32 &&
40713       VT.getVectorElementType() != MVT::f64)
40714     return SDValue();
40715 
40716   SDValue N0 = N->getOperand(0);
40717   SDValue N1 = N->getOperand(1);
40718 
40719   // Check that both sources are concats with undef.
40720   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
40721       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
40722       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
40723       !N1.getOperand(1).isUndef())
40724     return SDValue();
40725 
40726   // Construct the new shuffle mask. Elements from the first source retain their
40727   // index, but elements from the second source no longer need to skip an undef.
40728   SmallVector<int, 8> Mask;
40729   int NumElts = VT.getVectorNumElements();
40730 
40731   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
40732   for (int Elt : SVOp->getMask())
40733     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
40734 
40735   SDLoc DL(N);
40736   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
40737                                N1.getOperand(0));
40738   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
40739 }
40740 
40741 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
40742 /// low half of each source vector and does not set any high half elements in
40743 /// the destination vector, narrow the shuffle to half its original size.
40744 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
40745   if (!Shuf->getValueType(0).isSimple())
40746     return SDValue();
40747   MVT VT = Shuf->getSimpleValueType(0);
40748   if (!VT.is256BitVector() && !VT.is512BitVector())
40749     return SDValue();
40750 
40751   // See if we can ignore all of the high elements of the shuffle.
40752   ArrayRef<int> Mask = Shuf->getMask();
40753   if (!isUndefUpperHalf(Mask))
40754     return SDValue();
40755 
40756   // Check if the shuffle mask accesses only the low half of each input vector
40757   // (half-index output is 0 or 2).
40758   int HalfIdx1, HalfIdx2;
40759   SmallVector<int, 8> HalfMask(Mask.size() / 2);
40760   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
40761       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
40762     return SDValue();
40763 
40764   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
40765   // The trick is knowing that all of the insert/extract are actually free
40766   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
40767   // of narrow inputs into a narrow output, and that is always cheaper than
40768   // the wide shuffle that we started with.
40769   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
40770                                Shuf->getOperand(1), HalfMask, HalfIdx1,
40771                                HalfIdx2, false, DAG, /*UseConcat*/true);
40772 }
40773 
40774 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
40775                               TargetLowering::DAGCombinerInfo &DCI,
40776                               const X86Subtarget &Subtarget) {
40777   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
40778     if (SDValue V = narrowShuffle(Shuf, DAG))
40779       return V;
40780 
40781   // If we have legalized the vector types, look for blends of FADD and FSUB
40782   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
40783   SDLoc dl(N);
40784   EVT VT = N->getValueType(0);
40785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40786   if (TLI.isTypeLegal(VT))
40787     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
40788       return AddSub;
40789 
40790   // Attempt to combine into a vector load/broadcast.
40791   if (SDValue LD = combineToConsecutiveLoads(
40792           VT, SDValue(N, 0), dl, DAG, Subtarget, /*IsAfterLegalize*/ true))
40793     return LD;
40794 
40795   // For AVX2, we sometimes want to combine
40796   // (vector_shuffle <mask> (concat_vectors t1, undef)
40797   //                        (concat_vectors t2, undef))
40798   // Into:
40799   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
40800   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
40801   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
40802     return ShufConcat;
40803 
40804   if (isTargetShuffle(N->getOpcode())) {
40805     SDValue Op(N, 0);
40806     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
40807       return Shuffle;
40808 
40809     // Try recursively combining arbitrary sequences of x86 shuffle
40810     // instructions into higher-order shuffles. We do this after combining
40811     // specific PSHUF instruction sequences into their minimal form so that we
40812     // can evaluate how many specialized shuffle instructions are involved in
40813     // a particular chain.
40814     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
40815       return Res;
40816 
40817     // Simplify source operands based on shuffle mask.
40818     // TODO - merge this into combineX86ShufflesRecursively.
40819     APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
40820     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, DCI))
40821       return SDValue(N, 0);
40822 
40823     // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
40824     // Perform this after other shuffle combines to allow inner shuffles to be
40825     // combined away first.
40826     if (SDValue BinOp = canonicalizeShuffleWithBinOps(Op, DAG, dl))
40827       return BinOp;
40828   }
40829 
40830   return SDValue();
40831 }
40832 
40833 // Simplify variable target shuffle masks based on the demanded elements.
40834 // TODO: Handle DemandedBits in mask indices as well?
40835 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
40836     SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
40837     TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
40838   // If we're demanding all elements don't bother trying to simplify the mask.
40839   unsigned NumElts = DemandedElts.getBitWidth();
40840   if (DemandedElts.isAllOnes())
40841     return false;
40842 
40843   SDValue Mask = Op.getOperand(MaskIndex);
40844   if (!Mask.hasOneUse())
40845     return false;
40846 
40847   // Attempt to generically simplify the variable shuffle mask.
40848   APInt MaskUndef, MaskZero;
40849   if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
40850                                  Depth + 1))
40851     return true;
40852 
40853   // Attempt to extract+simplify a (constant pool load) shuffle mask.
40854   // TODO: Support other types from getTargetShuffleMaskIndices?
40855   SDValue BC = peekThroughOneUseBitcasts(Mask);
40856   EVT BCVT = BC.getValueType();
40857   auto *Load = dyn_cast<LoadSDNode>(BC);
40858   if (!Load)
40859     return false;
40860 
40861   const Constant *C = getTargetConstantFromNode(Load);
40862   if (!C)
40863     return false;
40864 
40865   Type *CTy = C->getType();
40866   if (!CTy->isVectorTy() ||
40867       CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
40868     return false;
40869 
40870   // Handle scaling for i64 elements on 32-bit targets.
40871   unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
40872   if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
40873     return false;
40874   unsigned Scale = NumCstElts / NumElts;
40875 
40876   // Simplify mask if we have an undemanded element that is not undef.
40877   bool Simplified = false;
40878   SmallVector<Constant *, 32> ConstVecOps;
40879   for (unsigned i = 0; i != NumCstElts; ++i) {
40880     Constant *Elt = C->getAggregateElement(i);
40881     if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
40882       ConstVecOps.push_back(UndefValue::get(Elt->getType()));
40883       Simplified = true;
40884       continue;
40885     }
40886     ConstVecOps.push_back(Elt);
40887   }
40888   if (!Simplified)
40889     return false;
40890 
40891   // Generate new constant pool entry + legalize immediately for the load.
40892   SDLoc DL(Op);
40893   SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
40894   SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
40895   SDValue NewMask = TLO.DAG.getLoad(
40896       BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
40897       MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
40898       Load->getAlign());
40899   return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
40900 }
40901 
40902 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
40903     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
40904     TargetLoweringOpt &TLO, unsigned Depth) const {
40905   int NumElts = DemandedElts.getBitWidth();
40906   unsigned Opc = Op.getOpcode();
40907   EVT VT = Op.getValueType();
40908 
40909   // Handle special case opcodes.
40910   switch (Opc) {
40911   case X86ISD::PMULDQ:
40912   case X86ISD::PMULUDQ: {
40913     APInt LHSUndef, LHSZero;
40914     APInt RHSUndef, RHSZero;
40915     SDValue LHS = Op.getOperand(0);
40916     SDValue RHS = Op.getOperand(1);
40917     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
40918                                    Depth + 1))
40919       return true;
40920     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
40921                                    Depth + 1))
40922       return true;
40923     // Multiply by zero.
40924     KnownZero = LHSZero | RHSZero;
40925     break;
40926   }
40927   case X86ISD::VPMADDWD: {
40928     APInt LHSUndef, LHSZero;
40929     APInt RHSUndef, RHSZero;
40930     SDValue LHS = Op.getOperand(0);
40931     SDValue RHS = Op.getOperand(1);
40932     APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, 2 * NumElts);
40933 
40934     if (SimplifyDemandedVectorElts(LHS, DemandedSrcElts, LHSUndef, LHSZero, TLO,
40935                                    Depth + 1))
40936       return true;
40937     if (SimplifyDemandedVectorElts(RHS, DemandedSrcElts, RHSUndef, RHSZero, TLO,
40938                                    Depth + 1))
40939       return true;
40940 
40941     // TODO: Multiply by zero.
40942 
40943     // If RHS/LHS elements are known zero then we don't need the LHS/RHS equivalent.
40944     APInt DemandedLHSElts = DemandedSrcElts & ~RHSZero;
40945     if (SimplifyDemandedVectorElts(LHS, DemandedLHSElts, LHSUndef, LHSZero, TLO,
40946                                    Depth + 1))
40947       return true;
40948     APInt DemandedRHSElts = DemandedSrcElts & ~LHSZero;
40949     if (SimplifyDemandedVectorElts(RHS, DemandedRHSElts, RHSUndef, RHSZero, TLO,
40950                                    Depth + 1))
40951       return true;
40952     break;
40953   }
40954   case X86ISD::PSADBW: {
40955     SDValue LHS = Op.getOperand(0);
40956     SDValue RHS = Op.getOperand(1);
40957     assert(VT.getScalarType() == MVT::i64 &&
40958            LHS.getValueType() == RHS.getValueType() &&
40959            LHS.getValueType().getScalarType() == MVT::i8 &&
40960            "Unexpected PSADBW types");
40961 
40962     // Aggressively peek through ops to get at the demanded elts.
40963     if (!DemandedElts.isAllOnes()) {
40964       unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
40965       APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
40966       SDValue NewLHS = SimplifyMultipleUseDemandedVectorElts(
40967           LHS, DemandedSrcElts, TLO.DAG, Depth + 1);
40968       SDValue NewRHS = SimplifyMultipleUseDemandedVectorElts(
40969           RHS, DemandedSrcElts, TLO.DAG, Depth + 1);
40970       if (NewLHS || NewRHS) {
40971         NewLHS = NewLHS ? NewLHS : LHS;
40972         NewRHS = NewRHS ? NewRHS : RHS;
40973         return TLO.CombineTo(
40974             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
40975       }
40976     }
40977     break;
40978   }
40979   case X86ISD::VSHL:
40980   case X86ISD::VSRL:
40981   case X86ISD::VSRA: {
40982     // We only need the bottom 64-bits of the (128-bit) shift amount.
40983     SDValue Amt = Op.getOperand(1);
40984     MVT AmtVT = Amt.getSimpleValueType();
40985     assert(AmtVT.is128BitVector() && "Unexpected value type");
40986 
40987     // If we reuse the shift amount just for sse shift amounts then we know that
40988     // only the bottom 64-bits are only ever used.
40989     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
40990       unsigned UseOpc = Use->getOpcode();
40991       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
40992               UseOpc == X86ISD::VSRA) &&
40993              Use->getOperand(0) != Amt;
40994     });
40995 
40996     APInt AmtUndef, AmtZero;
40997     unsigned NumAmtElts = AmtVT.getVectorNumElements();
40998     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
40999     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
41000                                    Depth + 1, AssumeSingleUse))
41001       return true;
41002     LLVM_FALLTHROUGH;
41003   }
41004   case X86ISD::VSHLI:
41005   case X86ISD::VSRLI:
41006   case X86ISD::VSRAI: {
41007     SDValue Src = Op.getOperand(0);
41008     APInt SrcUndef;
41009     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
41010                                    Depth + 1))
41011       return true;
41012 
41013     // Fold shift(0,x) -> 0
41014     if (DemandedElts.isSubsetOf(KnownZero))
41015       return TLO.CombineTo(
41016           Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
41017 
41018     // Aggressively peek through ops to get at the demanded elts.
41019     if (!DemandedElts.isAllOnes())
41020       if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
41021               Src, DemandedElts, TLO.DAG, Depth + 1))
41022         return TLO.CombineTo(
41023             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
41024     break;
41025   }
41026   case X86ISD::VPSHA:
41027   case X86ISD::VPSHL:
41028   case X86ISD::VSHLV:
41029   case X86ISD::VSRLV:
41030   case X86ISD::VSRAV: {
41031     APInt LHSUndef, LHSZero;
41032     APInt RHSUndef, RHSZero;
41033     SDValue LHS = Op.getOperand(0);
41034     SDValue RHS = Op.getOperand(1);
41035     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
41036                                    Depth + 1))
41037       return true;
41038 
41039     // Fold shift(0,x) -> 0
41040     if (DemandedElts.isSubsetOf(LHSZero))
41041       return TLO.CombineTo(
41042           Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
41043 
41044     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
41045                                    Depth + 1))
41046       return true;
41047 
41048     KnownZero = LHSZero;
41049     break;
41050   }
41051   case X86ISD::KSHIFTL: {
41052     SDValue Src = Op.getOperand(0);
41053     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
41054     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
41055     unsigned ShiftAmt = Amt->getZExtValue();
41056 
41057     if (ShiftAmt == 0)
41058       return TLO.CombineTo(Op, Src);
41059 
41060     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
41061     // single shift.  We can do this if the bottom bits (which are shifted
41062     // out) are never demanded.
41063     if (Src.getOpcode() == X86ISD::KSHIFTR) {
41064       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
41065         unsigned C1 = Src.getConstantOperandVal(1);
41066         unsigned NewOpc = X86ISD::KSHIFTL;
41067         int Diff = ShiftAmt - C1;
41068         if (Diff < 0) {
41069           Diff = -Diff;
41070           NewOpc = X86ISD::KSHIFTR;
41071         }
41072 
41073         SDLoc dl(Op);
41074         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
41075         return TLO.CombineTo(
41076             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
41077       }
41078     }
41079 
41080     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
41081     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
41082                                    Depth + 1))
41083       return true;
41084 
41085     KnownUndef <<= ShiftAmt;
41086     KnownZero <<= ShiftAmt;
41087     KnownZero.setLowBits(ShiftAmt);
41088     break;
41089   }
41090   case X86ISD::KSHIFTR: {
41091     SDValue Src = Op.getOperand(0);
41092     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
41093     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
41094     unsigned ShiftAmt = Amt->getZExtValue();
41095 
41096     if (ShiftAmt == 0)
41097       return TLO.CombineTo(Op, Src);
41098 
41099     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
41100     // single shift.  We can do this if the top bits (which are shifted
41101     // out) are never demanded.
41102     if (Src.getOpcode() == X86ISD::KSHIFTL) {
41103       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
41104         unsigned C1 = Src.getConstantOperandVal(1);
41105         unsigned NewOpc = X86ISD::KSHIFTR;
41106         int Diff = ShiftAmt - C1;
41107         if (Diff < 0) {
41108           Diff = -Diff;
41109           NewOpc = X86ISD::KSHIFTL;
41110         }
41111 
41112         SDLoc dl(Op);
41113         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
41114         return TLO.CombineTo(
41115             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
41116       }
41117     }
41118 
41119     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
41120     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
41121                                    Depth + 1))
41122       return true;
41123 
41124     KnownUndef.lshrInPlace(ShiftAmt);
41125     KnownZero.lshrInPlace(ShiftAmt);
41126     KnownZero.setHighBits(ShiftAmt);
41127     break;
41128   }
41129   case X86ISD::ANDNP: {
41130     // ANDNP = (~LHS & RHS);
41131     SDValue LHS = Op.getOperand(0);
41132     SDValue RHS = Op.getOperand(1);
41133 
41134     auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
41135       APInt UndefElts;
41136       SmallVector<APInt> EltBits;
41137       int NumElts = VT.getVectorNumElements();
41138       int EltSizeInBits = VT.getScalarSizeInBits();
41139       APInt OpBits = APInt::getAllOnes(EltSizeInBits);
41140       APInt OpElts = DemandedElts;
41141       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
41142                                         EltBits)) {
41143         OpBits.clearAllBits();
41144         OpElts.clearAllBits();
41145         for (int I = 0; I != NumElts; ++I) {
41146           if (!DemandedElts[I])
41147             continue;
41148           if (UndefElts[I]) {
41149             // We can't assume an undef src element gives an undef dst - the
41150             // other src might be zero.
41151             OpBits.setAllBits();
41152             OpElts.setBit(I);
41153           } else if ((Invert && !EltBits[I].isAllOnes()) ||
41154                      (!Invert && !EltBits[I].isZero())) {
41155             OpBits |= Invert ? ~EltBits[I] : EltBits[I];
41156             OpElts.setBit(I);
41157           }
41158         }
41159       }
41160       return std::make_pair(OpBits, OpElts);
41161     };
41162     std::pair<APInt, APInt> DemandLHS = GetDemandedMasks(RHS);
41163     std::pair<APInt, APInt> DemandRHS = GetDemandedMasks(LHS, true);
41164 
41165     APInt LHSUndef, LHSZero;
41166     APInt RHSUndef, RHSZero;
41167     if (SimplifyDemandedVectorElts(LHS, DemandLHS.second, LHSUndef, LHSZero,
41168                                    TLO, Depth + 1))
41169       return true;
41170     if (SimplifyDemandedVectorElts(RHS, DemandRHS.second, RHSUndef, RHSZero,
41171                                    TLO, Depth + 1))
41172       return true;
41173 
41174     if (!DemandedElts.isAllOnes()) {
41175       SDValue NewLHS = SimplifyMultipleUseDemandedBits(
41176           LHS, DemandLHS.first, DemandLHS.second, TLO.DAG, Depth + 1);
41177       SDValue NewRHS = SimplifyMultipleUseDemandedBits(
41178           RHS, DemandRHS.first, DemandRHS.second, TLO.DAG, Depth + 1);
41179       if (NewLHS || NewRHS) {
41180         NewLHS = NewLHS ? NewLHS : LHS;
41181         NewRHS = NewRHS ? NewRHS : RHS;
41182         return TLO.CombineTo(
41183             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
41184       }
41185     }
41186     break;
41187   }
41188   case X86ISD::CVTSI2P:
41189   case X86ISD::CVTUI2P: {
41190     SDValue Src = Op.getOperand(0);
41191     MVT SrcVT = Src.getSimpleValueType();
41192     APInt SrcUndef, SrcZero;
41193     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
41194     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
41195                                    Depth + 1))
41196       return true;
41197     break;
41198   }
41199   case X86ISD::PACKSS:
41200   case X86ISD::PACKUS: {
41201     SDValue N0 = Op.getOperand(0);
41202     SDValue N1 = Op.getOperand(1);
41203 
41204     APInt DemandedLHS, DemandedRHS;
41205     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
41206 
41207     APInt LHSUndef, LHSZero;
41208     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
41209                                    Depth + 1))
41210       return true;
41211     APInt RHSUndef, RHSZero;
41212     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
41213                                    Depth + 1))
41214       return true;
41215 
41216     // TODO - pass on known zero/undef.
41217 
41218     // Aggressively peek through ops to get at the demanded elts.
41219     // TODO - we should do this for all target/faux shuffles ops.
41220     if (!DemandedElts.isAllOnes()) {
41221       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
41222                                                             TLO.DAG, Depth + 1);
41223       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
41224                                                             TLO.DAG, Depth + 1);
41225       if (NewN0 || NewN1) {
41226         NewN0 = NewN0 ? NewN0 : N0;
41227         NewN1 = NewN1 ? NewN1 : N1;
41228         return TLO.CombineTo(Op,
41229                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
41230       }
41231     }
41232     break;
41233   }
41234   case X86ISD::HADD:
41235   case X86ISD::HSUB:
41236   case X86ISD::FHADD:
41237   case X86ISD::FHSUB: {
41238     SDValue N0 = Op.getOperand(0);
41239     SDValue N1 = Op.getOperand(1);
41240 
41241     APInt DemandedLHS, DemandedRHS;
41242     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
41243 
41244     APInt LHSUndef, LHSZero;
41245     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
41246                                    Depth + 1))
41247       return true;
41248     APInt RHSUndef, RHSZero;
41249     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
41250                                    Depth + 1))
41251       return true;
41252 
41253     // TODO - pass on known zero/undef.
41254 
41255     // Aggressively peek through ops to get at the demanded elts.
41256     // TODO: Handle repeated operands.
41257     if (N0 != N1 && !DemandedElts.isAllOnes()) {
41258       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
41259                                                             TLO.DAG, Depth + 1);
41260       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
41261                                                             TLO.DAG, Depth + 1);
41262       if (NewN0 || NewN1) {
41263         NewN0 = NewN0 ? NewN0 : N0;
41264         NewN1 = NewN1 ? NewN1 : N1;
41265         return TLO.CombineTo(Op,
41266                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
41267       }
41268     }
41269     break;
41270   }
41271   case X86ISD::VTRUNC:
41272   case X86ISD::VTRUNCS:
41273   case X86ISD::VTRUNCUS: {
41274     SDValue Src = Op.getOperand(0);
41275     MVT SrcVT = Src.getSimpleValueType();
41276     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
41277     APInt SrcUndef, SrcZero;
41278     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
41279                                    Depth + 1))
41280       return true;
41281     KnownZero = SrcZero.zextOrTrunc(NumElts);
41282     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
41283     break;
41284   }
41285   case X86ISD::BLENDV: {
41286     APInt SelUndef, SelZero;
41287     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
41288                                    SelZero, TLO, Depth + 1))
41289       return true;
41290 
41291     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
41292     APInt LHSUndef, LHSZero;
41293     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
41294                                    LHSZero, TLO, Depth + 1))
41295       return true;
41296 
41297     APInt RHSUndef, RHSZero;
41298     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
41299                                    RHSZero, TLO, Depth + 1))
41300       return true;
41301 
41302     KnownZero = LHSZero & RHSZero;
41303     KnownUndef = LHSUndef & RHSUndef;
41304     break;
41305   }
41306   case X86ISD::VZEXT_MOVL: {
41307     // If upper demanded elements are already zero then we have nothing to do.
41308     SDValue Src = Op.getOperand(0);
41309     APInt DemandedUpperElts = DemandedElts;
41310     DemandedUpperElts.clearLowBits(1);
41311     if (TLO.DAG.MaskedVectorIsZero(Src, DemandedUpperElts, Depth + 1))
41312       return TLO.CombineTo(Op, Src);
41313     break;
41314   }
41315   case X86ISD::VBROADCAST: {
41316     SDValue Src = Op.getOperand(0);
41317     MVT SrcVT = Src.getSimpleValueType();
41318     if (!SrcVT.isVector())
41319       break;
41320     // Don't bother broadcasting if we just need the 0'th element.
41321     if (DemandedElts == 1) {
41322       if (Src.getValueType() != VT)
41323         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
41324                              SDLoc(Op));
41325       return TLO.CombineTo(Op, Src);
41326     }
41327     APInt SrcUndef, SrcZero;
41328     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
41329     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
41330                                    Depth + 1))
41331       return true;
41332     // Aggressively peek through src to get at the demanded elt.
41333     // TODO - we should do this for all target/faux shuffles ops.
41334     if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
41335             Src, SrcElts, TLO.DAG, Depth + 1))
41336       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
41337     break;
41338   }
41339   case X86ISD::VPERMV:
41340     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
41341                                                    Depth))
41342       return true;
41343     break;
41344   case X86ISD::PSHUFB:
41345   case X86ISD::VPERMV3:
41346   case X86ISD::VPERMILPV:
41347     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
41348                                                    Depth))
41349       return true;
41350     break;
41351   case X86ISD::VPPERM:
41352   case X86ISD::VPERMIL2:
41353     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
41354                                                    Depth))
41355       return true;
41356     break;
41357   }
41358 
41359   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
41360   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
41361   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
41362   if ((VT.is256BitVector() || VT.is512BitVector()) &&
41363       DemandedElts.lshr(NumElts / 2) == 0) {
41364     unsigned SizeInBits = VT.getSizeInBits();
41365     unsigned ExtSizeInBits = SizeInBits / 2;
41366 
41367     // See if 512-bit ops only use the bottom 128-bits.
41368     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
41369       ExtSizeInBits = SizeInBits / 4;
41370 
41371     switch (Opc) {
41372       // Scalar broadcast.
41373     case X86ISD::VBROADCAST: {
41374       SDLoc DL(Op);
41375       SDValue Src = Op.getOperand(0);
41376       if (Src.getValueSizeInBits() > ExtSizeInBits)
41377         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
41378       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
41379                                     ExtSizeInBits / VT.getScalarSizeInBits());
41380       SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
41381       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
41382                                                TLO.DAG, DL, ExtSizeInBits));
41383     }
41384     case X86ISD::VBROADCAST_LOAD: {
41385       SDLoc DL(Op);
41386       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
41387       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
41388                                     ExtSizeInBits / VT.getScalarSizeInBits());
41389       SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
41390       SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
41391       SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
41392           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
41393           MemIntr->getMemOperand());
41394       TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
41395                                            Bcst.getValue(1));
41396       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
41397                                                TLO.DAG, DL, ExtSizeInBits));
41398     }
41399       // Subvector broadcast.
41400     case X86ISD::SUBV_BROADCAST_LOAD: {
41401       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
41402       EVT MemVT = MemIntr->getMemoryVT();
41403       if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
41404         SDLoc DL(Op);
41405         SDValue Ld =
41406             TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
41407                             MemIntr->getBasePtr(), MemIntr->getMemOperand());
41408         TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
41409                                              Ld.getValue(1));
41410         return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
41411                                                  TLO.DAG, DL, ExtSizeInBits));
41412       } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
41413         SDLoc DL(Op);
41414         EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
41415                                       ExtSizeInBits / VT.getScalarSizeInBits());
41416         if (SDValue BcstLd =
41417                 getBROADCAST_LOAD(Opc, DL, BcstVT, MemVT, MemIntr, 0, TLO.DAG))
41418           return TLO.CombineTo(Op,
41419                                insertSubVector(TLO.DAG.getUNDEF(VT), BcstLd, 0,
41420                                                TLO.DAG, DL, ExtSizeInBits));
41421       }
41422       break;
41423     }
41424       // Byte shifts by immediate.
41425     case X86ISD::VSHLDQ:
41426     case X86ISD::VSRLDQ:
41427       // Shift by uniform.
41428     case X86ISD::VSHL:
41429     case X86ISD::VSRL:
41430     case X86ISD::VSRA:
41431       // Shift by immediate.
41432     case X86ISD::VSHLI:
41433     case X86ISD::VSRLI:
41434     case X86ISD::VSRAI: {
41435       SDLoc DL(Op);
41436       SDValue Ext0 =
41437           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
41438       SDValue ExtOp =
41439           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
41440       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41441       SDValue Insert =
41442           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
41443       return TLO.CombineTo(Op, Insert);
41444     }
41445     case X86ISD::VPERMI: {
41446       // Simplify PERMPD/PERMQ to extract_subvector.
41447       // TODO: This should be done in shuffle combining.
41448       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
41449         SmallVector<int, 4> Mask;
41450         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
41451         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
41452           SDLoc DL(Op);
41453           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
41454           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41455           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
41456           return TLO.CombineTo(Op, Insert);
41457         }
41458       }
41459       break;
41460     }
41461     case X86ISD::VPERM2X128: {
41462       // Simplify VPERM2F128/VPERM2I128 to extract_subvector.
41463       SDLoc DL(Op);
41464       unsigned LoMask = Op.getConstantOperandVal(2) & 0xF;
41465       if (LoMask & 0x8)
41466         return TLO.CombineTo(
41467             Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, DL));
41468       unsigned EltIdx = (LoMask & 0x1) * (NumElts / 2);
41469       unsigned SrcIdx = (LoMask & 0x2) >> 1;
41470       SDValue ExtOp =
41471           extractSubVector(Op.getOperand(SrcIdx), EltIdx, TLO.DAG, DL, 128);
41472       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41473       SDValue Insert =
41474           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
41475       return TLO.CombineTo(Op, Insert);
41476     }
41477       // Zero upper elements.
41478     case X86ISD::VZEXT_MOVL:
41479       // Target unary shuffles by immediate:
41480     case X86ISD::PSHUFD:
41481     case X86ISD::PSHUFLW:
41482     case X86ISD::PSHUFHW:
41483     case X86ISD::VPERMILPI:
41484       // (Non-Lane Crossing) Target Shuffles.
41485     case X86ISD::VPERMILPV:
41486     case X86ISD::VPERMIL2:
41487     case X86ISD::PSHUFB:
41488     case X86ISD::UNPCKL:
41489     case X86ISD::UNPCKH:
41490     case X86ISD::BLENDI:
41491       // Integer ops.
41492     case X86ISD::PACKSS:
41493     case X86ISD::PACKUS:
41494       // Horizontal Ops.
41495     case X86ISD::HADD:
41496     case X86ISD::HSUB:
41497     case X86ISD::FHADD:
41498     case X86ISD::FHSUB: {
41499       SDLoc DL(Op);
41500       SmallVector<SDValue, 4> Ops;
41501       for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
41502         SDValue SrcOp = Op.getOperand(i);
41503         EVT SrcVT = SrcOp.getValueType();
41504         assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
41505                "Unsupported vector size");
41506         Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
41507                                                           ExtSizeInBits)
41508                                        : SrcOp);
41509       }
41510       MVT ExtVT = VT.getSimpleVT();
41511       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
41512                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
41513       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
41514       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41515       SDValue Insert =
41516           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
41517       return TLO.CombineTo(Op, Insert);
41518     }
41519     }
41520   }
41521 
41522   // For splats, unless we *only* demand the 0'th element,
41523   // stop attempts at simplification here, we aren't going to improve things,
41524   // this is better than any potential shuffle.
41525   if (!DemandedElts.isOne() && TLO.DAG.isSplatValue(Op, /*AllowUndefs*/false))
41526     return false;
41527 
41528   // Get target/faux shuffle mask.
41529   APInt OpUndef, OpZero;
41530   SmallVector<int, 64> OpMask;
41531   SmallVector<SDValue, 2> OpInputs;
41532   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
41533                               OpZero, TLO.DAG, Depth, false))
41534     return false;
41535 
41536   // Shuffle inputs must be the same size as the result.
41537   if (OpMask.size() != (unsigned)NumElts ||
41538       llvm::any_of(OpInputs, [VT](SDValue V) {
41539         return VT.getSizeInBits() != V.getValueSizeInBits() ||
41540                !V.getValueType().isVector();
41541       }))
41542     return false;
41543 
41544   KnownZero = OpZero;
41545   KnownUndef = OpUndef;
41546 
41547   // Check if shuffle mask can be simplified to undef/zero/identity.
41548   int NumSrcs = OpInputs.size();
41549   for (int i = 0; i != NumElts; ++i)
41550     if (!DemandedElts[i])
41551       OpMask[i] = SM_SentinelUndef;
41552 
41553   if (isUndefInRange(OpMask, 0, NumElts)) {
41554     KnownUndef.setAllBits();
41555     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
41556   }
41557   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
41558     KnownZero.setAllBits();
41559     return TLO.CombineTo(
41560         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
41561   }
41562   for (int Src = 0; Src != NumSrcs; ++Src)
41563     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
41564       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
41565 
41566   // Attempt to simplify inputs.
41567   for (int Src = 0; Src != NumSrcs; ++Src) {
41568     // TODO: Support inputs of different types.
41569     if (OpInputs[Src].getValueType() != VT)
41570       continue;
41571 
41572     int Lo = Src * NumElts;
41573     APInt SrcElts = APInt::getZero(NumElts);
41574     for (int i = 0; i != NumElts; ++i)
41575       if (DemandedElts[i]) {
41576         int M = OpMask[i] - Lo;
41577         if (0 <= M && M < NumElts)
41578           SrcElts.setBit(M);
41579       }
41580 
41581     // TODO - Propagate input undef/zero elts.
41582     APInt SrcUndef, SrcZero;
41583     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
41584                                    TLO, Depth + 1))
41585       return true;
41586   }
41587 
41588   // If we don't demand all elements, then attempt to combine to a simpler
41589   // shuffle.
41590   // We need to convert the depth to something combineX86ShufflesRecursively
41591   // can handle - so pretend its Depth == 0 again, and reduce the max depth
41592   // to match. This prevents combineX86ShuffleChain from returning a
41593   // combined shuffle that's the same as the original root, causing an
41594   // infinite loop.
41595   if (!DemandedElts.isAllOnes()) {
41596     assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range");
41597 
41598     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
41599     for (int i = 0; i != NumElts; ++i)
41600       if (DemandedElts[i])
41601         DemandedMask[i] = i;
41602 
41603     SDValue NewShuffle = combineX86ShufflesRecursively(
41604         {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
41605         /*HasVarMask*/ false,
41606         /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, TLO.DAG,
41607         Subtarget);
41608     if (NewShuffle)
41609       return TLO.CombineTo(Op, NewShuffle);
41610   }
41611 
41612   return false;
41613 }
41614 
41615 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
41616     SDValue Op, const APInt &OriginalDemandedBits,
41617     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
41618     unsigned Depth) const {
41619   EVT VT = Op.getValueType();
41620   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
41621   unsigned Opc = Op.getOpcode();
41622   switch(Opc) {
41623   case X86ISD::VTRUNC: {
41624     KnownBits KnownOp;
41625     SDValue Src = Op.getOperand(0);
41626     MVT SrcVT = Src.getSimpleValueType();
41627 
41628     // Simplify the input, using demanded bit information.
41629     APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
41630     APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
41631     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
41632       return true;
41633     break;
41634   }
41635   case X86ISD::PMULDQ:
41636   case X86ISD::PMULUDQ: {
41637     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
41638     KnownBits KnownOp;
41639     SDValue LHS = Op.getOperand(0);
41640     SDValue RHS = Op.getOperand(1);
41641 
41642     // Don't mask bits on 32-bit AVX512 targets which might lose a broadcast.
41643     // FIXME: Can we bound this better?
41644     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
41645     APInt DemandedMaskLHS = APInt::getAllOnes(64);
41646     APInt DemandedMaskRHS = APInt::getAllOnes(64);
41647 
41648     bool Is32BitAVX512 = !Subtarget.is64Bit() && Subtarget.hasAVX512();
41649     if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(LHS))
41650       DemandedMaskLHS = DemandedMask;
41651     if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(RHS))
41652       DemandedMaskRHS = DemandedMask;
41653 
41654     if (SimplifyDemandedBits(LHS, DemandedMaskLHS, OriginalDemandedElts,
41655                              KnownOp, TLO, Depth + 1))
41656       return true;
41657     if (SimplifyDemandedBits(RHS, DemandedMaskRHS, OriginalDemandedElts,
41658                              KnownOp, TLO, Depth + 1))
41659       return true;
41660 
41661     // Aggressively peek through ops to get at the demanded low bits.
41662     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
41663         LHS, DemandedMaskLHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
41664     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
41665         RHS, DemandedMaskRHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
41666     if (DemandedLHS || DemandedRHS) {
41667       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
41668       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
41669       return TLO.CombineTo(
41670           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
41671     }
41672     break;
41673   }
41674   case X86ISD::VSHLI: {
41675     SDValue Op0 = Op.getOperand(0);
41676 
41677     unsigned ShAmt = Op.getConstantOperandVal(1);
41678     if (ShAmt >= BitWidth)
41679       break;
41680 
41681     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
41682 
41683     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
41684     // single shift.  We can do this if the bottom bits (which are shifted
41685     // out) are never demanded.
41686     if (Op0.getOpcode() == X86ISD::VSRLI &&
41687         OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
41688       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
41689       if (Shift2Amt < BitWidth) {
41690         int Diff = ShAmt - Shift2Amt;
41691         if (Diff == 0)
41692           return TLO.CombineTo(Op, Op0.getOperand(0));
41693 
41694         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
41695         SDValue NewShift = TLO.DAG.getNode(
41696             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
41697             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
41698         return TLO.CombineTo(Op, NewShift);
41699       }
41700     }
41701 
41702     // If we are only demanding sign bits then we can use the shift source directly.
41703     unsigned NumSignBits =
41704         TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
41705     unsigned UpperDemandedBits =
41706         BitWidth - OriginalDemandedBits.countTrailingZeros();
41707     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
41708       return TLO.CombineTo(Op, Op0);
41709 
41710     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
41711                              TLO, Depth + 1))
41712       return true;
41713 
41714     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41715     Known.Zero <<= ShAmt;
41716     Known.One <<= ShAmt;
41717 
41718     // Low bits known zero.
41719     Known.Zero.setLowBits(ShAmt);
41720     return false;
41721   }
41722   case X86ISD::VSRLI: {
41723     unsigned ShAmt = Op.getConstantOperandVal(1);
41724     if (ShAmt >= BitWidth)
41725       break;
41726 
41727     APInt DemandedMask = OriginalDemandedBits << ShAmt;
41728 
41729     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
41730                              OriginalDemandedElts, Known, TLO, Depth + 1))
41731       return true;
41732 
41733     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41734     Known.Zero.lshrInPlace(ShAmt);
41735     Known.One.lshrInPlace(ShAmt);
41736 
41737     // High bits known zero.
41738     Known.Zero.setHighBits(ShAmt);
41739     return false;
41740   }
41741   case X86ISD::VSRAI: {
41742     SDValue Op0 = Op.getOperand(0);
41743     SDValue Op1 = Op.getOperand(1);
41744 
41745     unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
41746     if (ShAmt >= BitWidth)
41747       break;
41748 
41749     APInt DemandedMask = OriginalDemandedBits << ShAmt;
41750 
41751     // If we just want the sign bit then we don't need to shift it.
41752     if (OriginalDemandedBits.isSignMask())
41753       return TLO.CombineTo(Op, Op0);
41754 
41755     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
41756     if (Op0.getOpcode() == X86ISD::VSHLI &&
41757         Op.getOperand(1) == Op0.getOperand(1)) {
41758       SDValue Op00 = Op0.getOperand(0);
41759       unsigned NumSignBits =
41760           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
41761       if (ShAmt < NumSignBits)
41762         return TLO.CombineTo(Op, Op00);
41763     }
41764 
41765     // If any of the demanded bits are produced by the sign extension, we also
41766     // demand the input sign bit.
41767     if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
41768       DemandedMask.setSignBit();
41769 
41770     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
41771                              TLO, Depth + 1))
41772       return true;
41773 
41774     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41775     Known.Zero.lshrInPlace(ShAmt);
41776     Known.One.lshrInPlace(ShAmt);
41777 
41778     // If the input sign bit is known to be zero, or if none of the top bits
41779     // are demanded, turn this into an unsigned shift right.
41780     if (Known.Zero[BitWidth - ShAmt - 1] ||
41781         OriginalDemandedBits.countLeadingZeros() >= ShAmt)
41782       return TLO.CombineTo(
41783           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
41784 
41785     // High bits are known one.
41786     if (Known.One[BitWidth - ShAmt - 1])
41787       Known.One.setHighBits(ShAmt);
41788     return false;
41789   }
41790   case X86ISD::BLENDV: {
41791     SDValue Sel = Op.getOperand(0);
41792     SDValue LHS = Op.getOperand(1);
41793     SDValue RHS = Op.getOperand(2);
41794 
41795     APInt SignMask = APInt::getSignMask(BitWidth);
41796     SDValue NewSel = SimplifyMultipleUseDemandedBits(
41797         Sel, SignMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
41798     SDValue NewLHS = SimplifyMultipleUseDemandedBits(
41799         LHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
41800     SDValue NewRHS = SimplifyMultipleUseDemandedBits(
41801         RHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
41802 
41803     if (NewSel || NewLHS || NewRHS) {
41804       NewSel = NewSel ? NewSel : Sel;
41805       NewLHS = NewLHS ? NewLHS : LHS;
41806       NewRHS = NewRHS ? NewRHS : RHS;
41807       return TLO.CombineTo(Op, TLO.DAG.getNode(X86ISD::BLENDV, SDLoc(Op), VT,
41808                                                NewSel, NewLHS, NewRHS));
41809     }
41810     break;
41811   }
41812   case X86ISD::PEXTRB:
41813   case X86ISD::PEXTRW: {
41814     SDValue Vec = Op.getOperand(0);
41815     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
41816     MVT VecVT = Vec.getSimpleValueType();
41817     unsigned NumVecElts = VecVT.getVectorNumElements();
41818 
41819     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
41820       unsigned Idx = CIdx->getZExtValue();
41821       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
41822 
41823       // If we demand no bits from the vector then we must have demanded
41824       // bits from the implict zext - simplify to zero.
41825       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
41826       if (DemandedVecBits == 0)
41827         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
41828 
41829       APInt KnownUndef, KnownZero;
41830       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
41831       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
41832                                      KnownZero, TLO, Depth + 1))
41833         return true;
41834 
41835       KnownBits KnownVec;
41836       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
41837                                KnownVec, TLO, Depth + 1))
41838         return true;
41839 
41840       if (SDValue V = SimplifyMultipleUseDemandedBits(
41841               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
41842         return TLO.CombineTo(
41843             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
41844 
41845       Known = KnownVec.zext(BitWidth);
41846       return false;
41847     }
41848     break;
41849   }
41850   case X86ISD::PINSRB:
41851   case X86ISD::PINSRW: {
41852     SDValue Vec = Op.getOperand(0);
41853     SDValue Scl = Op.getOperand(1);
41854     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
41855     MVT VecVT = Vec.getSimpleValueType();
41856 
41857     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
41858       unsigned Idx = CIdx->getZExtValue();
41859       if (!OriginalDemandedElts[Idx])
41860         return TLO.CombineTo(Op, Vec);
41861 
41862       KnownBits KnownVec;
41863       APInt DemandedVecElts(OriginalDemandedElts);
41864       DemandedVecElts.clearBit(Idx);
41865       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
41866                                KnownVec, TLO, Depth + 1))
41867         return true;
41868 
41869       KnownBits KnownScl;
41870       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
41871       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
41872       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
41873         return true;
41874 
41875       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
41876       Known = KnownBits::commonBits(KnownVec, KnownScl);
41877       return false;
41878     }
41879     break;
41880   }
41881   case X86ISD::PACKSS:
41882     // PACKSS saturates to MIN/MAX integer values. So if we just want the
41883     // sign bit then we can just ask for the source operands sign bit.
41884     // TODO - add known bits handling.
41885     if (OriginalDemandedBits.isSignMask()) {
41886       APInt DemandedLHS, DemandedRHS;
41887       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
41888 
41889       KnownBits KnownLHS, KnownRHS;
41890       APInt SignMask = APInt::getSignMask(BitWidth * 2);
41891       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
41892                                KnownLHS, TLO, Depth + 1))
41893         return true;
41894       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
41895                                KnownRHS, TLO, Depth + 1))
41896         return true;
41897 
41898       // Attempt to avoid multi-use ops if we don't need anything from them.
41899       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
41900           Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
41901       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
41902           Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
41903       if (DemandedOp0 || DemandedOp1) {
41904         SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
41905         SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
41906         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
41907       }
41908     }
41909     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
41910     break;
41911   case X86ISD::VBROADCAST: {
41912     SDValue Src = Op.getOperand(0);
41913     MVT SrcVT = Src.getSimpleValueType();
41914     APInt DemandedElts = APInt::getOneBitSet(
41915         SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1, 0);
41916     if (SimplifyDemandedBits(Src, OriginalDemandedBits, DemandedElts, Known,
41917                              TLO, Depth + 1))
41918       return true;
41919     // If we don't need the upper bits, attempt to narrow the broadcast source.
41920     // Don't attempt this on AVX512 as it might affect broadcast folding.
41921     // TODO: Should we attempt this for i32/i16 splats? They tend to be slower.
41922     if ((BitWidth == 64) && SrcVT.isScalarInteger() && !Subtarget.hasAVX512() &&
41923         OriginalDemandedBits.countLeadingZeros() >= (BitWidth / 2) &&
41924         Src->hasOneUse()) {
41925       MVT NewSrcVT = MVT::getIntegerVT(BitWidth / 2);
41926       SDValue NewSrc =
41927           TLO.DAG.getNode(ISD::TRUNCATE, SDLoc(Src), NewSrcVT, Src);
41928       MVT NewVT = MVT::getVectorVT(NewSrcVT, VT.getVectorNumElements() * 2);
41929       SDValue NewBcst =
41930           TLO.DAG.getNode(X86ISD::VBROADCAST, SDLoc(Op), NewVT, NewSrc);
41931       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, NewBcst));
41932     }
41933     break;
41934   }
41935   case X86ISD::PCMPGT:
41936     // icmp sgt(0, R) == ashr(R, BitWidth-1).
41937     // iff we only need the sign bit then we can use R directly.
41938     if (OriginalDemandedBits.isSignMask() &&
41939         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
41940       return TLO.CombineTo(Op, Op.getOperand(1));
41941     break;
41942   case X86ISD::MOVMSK: {
41943     SDValue Src = Op.getOperand(0);
41944     MVT SrcVT = Src.getSimpleValueType();
41945     unsigned SrcBits = SrcVT.getScalarSizeInBits();
41946     unsigned NumElts = SrcVT.getVectorNumElements();
41947 
41948     // If we don't need the sign bits at all just return zero.
41949     if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
41950       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
41951 
41952     // See if we only demand bits from the lower 128-bit vector.
41953     if (SrcVT.is256BitVector() &&
41954         OriginalDemandedBits.getActiveBits() <= (NumElts / 2)) {
41955       SDValue NewSrc = extract128BitVector(Src, 0, TLO.DAG, SDLoc(Src));
41956       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
41957     }
41958 
41959     // Only demand the vector elements of the sign bits we need.
41960     APInt KnownUndef, KnownZero;
41961     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
41962     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
41963                                    TLO, Depth + 1))
41964       return true;
41965 
41966     Known.Zero = KnownZero.zext(BitWidth);
41967     Known.Zero.setHighBits(BitWidth - NumElts);
41968 
41969     // MOVMSK only uses the MSB from each vector element.
41970     KnownBits KnownSrc;
41971     APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
41972     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
41973                              Depth + 1))
41974       return true;
41975 
41976     if (KnownSrc.One[SrcBits - 1])
41977       Known.One.setLowBits(NumElts);
41978     else if (KnownSrc.Zero[SrcBits - 1])
41979       Known.Zero.setLowBits(NumElts);
41980 
41981     // Attempt to avoid multi-use os if we don't need anything from it.
41982     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
41983             Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
41984       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
41985     return false;
41986   }
41987   case X86ISD::BEXTR:
41988   case X86ISD::BEXTRI: {
41989     SDValue Op0 = Op.getOperand(0);
41990     SDValue Op1 = Op.getOperand(1);
41991 
41992     // Only bottom 16-bits of the control bits are required.
41993     if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
41994       // NOTE: SimplifyDemandedBits won't do this for constants.
41995       uint64_t Val1 = Cst1->getZExtValue();
41996       uint64_t MaskedVal1 = Val1 & 0xFFFF;
41997       if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
41998         SDLoc DL(Op);
41999         return TLO.CombineTo(
42000             Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
42001                                 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
42002       }
42003 
42004       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
42005       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
42006 
42007       // If the length is 0, the result is 0.
42008       if (Length == 0) {
42009         Known.setAllZero();
42010         return false;
42011       }
42012 
42013       if ((Shift + Length) <= BitWidth) {
42014         APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
42015         if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
42016           return true;
42017 
42018         Known = Known.extractBits(Length, Shift);
42019         Known = Known.zextOrTrunc(BitWidth);
42020         return false;
42021       }
42022     } else {
42023       assert(Opc == X86ISD::BEXTR && "Unexpected opcode!");
42024       KnownBits Known1;
42025       APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
42026       if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
42027         return true;
42028 
42029       // If the length is 0, replace with 0.
42030       KnownBits LengthBits = Known1.extractBits(8, 8);
42031       if (LengthBits.isZero())
42032         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
42033     }
42034 
42035     break;
42036   }
42037   case X86ISD::PDEP: {
42038     SDValue Op0 = Op.getOperand(0);
42039     SDValue Op1 = Op.getOperand(1);
42040 
42041     unsigned DemandedBitsLZ = OriginalDemandedBits.countLeadingZeros();
42042     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
42043 
42044     // If the demanded bits has leading zeroes, we don't demand those from the
42045     // mask.
42046     if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
42047       return true;
42048 
42049     // The number of possible 1s in the mask determines the number of LSBs of
42050     // operand 0 used. Undemanded bits from the mask don't matter so filter
42051     // them before counting.
42052     KnownBits Known2;
42053     uint64_t Count = (~Known.Zero & LoMask).countPopulation();
42054     APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
42055     if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
42056       return true;
42057 
42058     // Zeroes are retained from the mask, but not ones.
42059     Known.One.clearAllBits();
42060     // The result will have at least as many trailing zeros as the non-mask
42061     // operand since bits can only map to the same or higher bit position.
42062     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
42063     return false;
42064   }
42065   }
42066 
42067   return TargetLowering::SimplifyDemandedBitsForTargetNode(
42068       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
42069 }
42070 
42071 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
42072     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
42073     SelectionDAG &DAG, unsigned Depth) const {
42074   int NumElts = DemandedElts.getBitWidth();
42075   unsigned Opc = Op.getOpcode();
42076   EVT VT = Op.getValueType();
42077 
42078   switch (Opc) {
42079   case X86ISD::PINSRB:
42080   case X86ISD::PINSRW: {
42081     // If we don't demand the inserted element, return the base vector.
42082     SDValue Vec = Op.getOperand(0);
42083     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
42084     MVT VecVT = Vec.getSimpleValueType();
42085     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
42086         !DemandedElts[CIdx->getZExtValue()])
42087       return Vec;
42088     break;
42089   }
42090   case X86ISD::VSHLI: {
42091     // If we are only demanding sign bits then we can use the shift source
42092     // directly.
42093     SDValue Op0 = Op.getOperand(0);
42094     unsigned ShAmt = Op.getConstantOperandVal(1);
42095     unsigned BitWidth = DemandedBits.getBitWidth();
42096     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
42097     unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
42098     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
42099       return Op0;
42100     break;
42101   }
42102   case X86ISD::VSRAI:
42103     // iff we only need the sign bit then we can use the source directly.
42104     // TODO: generalize where we only demand extended signbits.
42105     if (DemandedBits.isSignMask())
42106       return Op.getOperand(0);
42107     break;
42108   case X86ISD::PCMPGT:
42109     // icmp sgt(0, R) == ashr(R, BitWidth-1).
42110     // iff we only need the sign bit then we can use R directly.
42111     if (DemandedBits.isSignMask() &&
42112         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
42113       return Op.getOperand(1);
42114     break;
42115   }
42116 
42117   APInt ShuffleUndef, ShuffleZero;
42118   SmallVector<int, 16> ShuffleMask;
42119   SmallVector<SDValue, 2> ShuffleOps;
42120   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
42121                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
42122     // If all the demanded elts are from one operand and are inline,
42123     // then we can use the operand directly.
42124     int NumOps = ShuffleOps.size();
42125     if (ShuffleMask.size() == (unsigned)NumElts &&
42126         llvm::all_of(ShuffleOps, [VT](SDValue V) {
42127           return VT.getSizeInBits() == V.getValueSizeInBits();
42128         })) {
42129 
42130       if (DemandedElts.isSubsetOf(ShuffleUndef))
42131         return DAG.getUNDEF(VT);
42132       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
42133         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
42134 
42135       // Bitmask that indicates which ops have only been accessed 'inline'.
42136       APInt IdentityOp = APInt::getAllOnes(NumOps);
42137       for (int i = 0; i != NumElts; ++i) {
42138         int M = ShuffleMask[i];
42139         if (!DemandedElts[i] || ShuffleUndef[i])
42140           continue;
42141         int OpIdx = M / NumElts;
42142         int EltIdx = M % NumElts;
42143         if (M < 0 || EltIdx != i) {
42144           IdentityOp.clearAllBits();
42145           break;
42146         }
42147         IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
42148         if (IdentityOp == 0)
42149           break;
42150       }
42151       assert((IdentityOp == 0 || IdentityOp.countPopulation() == 1) &&
42152              "Multiple identity shuffles detected");
42153 
42154       if (IdentityOp != 0)
42155         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countTrailingZeros()]);
42156     }
42157   }
42158 
42159   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
42160       Op, DemandedBits, DemandedElts, DAG, Depth);
42161 }
42162 
42163 bool X86TargetLowering::isSplatValueForTargetNode(SDValue Op,
42164                                                   const APInt &DemandedElts,
42165                                                   APInt &UndefElts,
42166                                                   unsigned Depth) const {
42167   unsigned NumElts = DemandedElts.getBitWidth();
42168   unsigned Opc = Op.getOpcode();
42169 
42170   switch (Opc) {
42171   case X86ISD::VBROADCAST:
42172   case X86ISD::VBROADCAST_LOAD:
42173     UndefElts = APInt::getNullValue(NumElts);
42174     return true;
42175   }
42176 
42177   return TargetLowering::isSplatValueForTargetNode(Op, DemandedElts, UndefElts,
42178                                                    Depth);
42179 }
42180 
42181 // Helper to peek through bitops/trunc/setcc to determine size of source vector.
42182 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
42183 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
42184                                       bool AllowTruncate) {
42185   switch (Src.getOpcode()) {
42186   case ISD::TRUNCATE:
42187     if (!AllowTruncate)
42188       return false;
42189     LLVM_FALLTHROUGH;
42190   case ISD::SETCC:
42191     return Src.getOperand(0).getValueSizeInBits() == Size;
42192   case ISD::AND:
42193   case ISD::XOR:
42194   case ISD::OR:
42195     return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate) &&
42196            checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate);
42197   }
42198   return false;
42199 }
42200 
42201 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
42202 static unsigned getAltBitOpcode(unsigned Opcode) {
42203   switch(Opcode) {
42204   case ISD::AND: return X86ISD::FAND;
42205   case ISD::OR: return X86ISD::FOR;
42206   case ISD::XOR: return X86ISD::FXOR;
42207   case X86ISD::ANDNP: return X86ISD::FANDN;
42208   }
42209   llvm_unreachable("Unknown bitwise opcode");
42210 }
42211 
42212 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
42213 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
42214                                           const SDLoc &DL) {
42215   EVT SrcVT = Src.getValueType();
42216   if (SrcVT != MVT::v4i1)
42217     return SDValue();
42218 
42219   switch (Src.getOpcode()) {
42220   case ISD::SETCC:
42221     if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
42222         ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
42223         cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
42224       SDValue Op0 = Src.getOperand(0);
42225       if (ISD::isNormalLoad(Op0.getNode()))
42226         return DAG.getBitcast(MVT::v4f32, Op0);
42227       if (Op0.getOpcode() == ISD::BITCAST &&
42228           Op0.getOperand(0).getValueType() == MVT::v4f32)
42229         return Op0.getOperand(0);
42230     }
42231     break;
42232   case ISD::AND:
42233   case ISD::XOR:
42234   case ISD::OR: {
42235     SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
42236     SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
42237     if (Op0 && Op1)
42238       return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
42239                          Op1);
42240     break;
42241   }
42242   }
42243   return SDValue();
42244 }
42245 
42246 // Helper to push sign extension of vXi1 SETCC result through bitops.
42247 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
42248                                           SDValue Src, const SDLoc &DL) {
42249   switch (Src.getOpcode()) {
42250   case ISD::SETCC:
42251   case ISD::TRUNCATE:
42252     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
42253   case ISD::AND:
42254   case ISD::XOR:
42255   case ISD::OR:
42256     return DAG.getNode(
42257         Src.getOpcode(), DL, SExtVT,
42258         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
42259         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
42260   }
42261   llvm_unreachable("Unexpected node type for vXi1 sign extension");
42262 }
42263 
42264 // Try to match patterns such as
42265 // (i16 bitcast (v16i1 x))
42266 // ->
42267 // (i16 movmsk (16i8 sext (v16i1 x)))
42268 // before the illegal vector is scalarized on subtargets that don't have legal
42269 // vxi1 types.
42270 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
42271                                   const SDLoc &DL,
42272                                   const X86Subtarget &Subtarget) {
42273   EVT SrcVT = Src.getValueType();
42274   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
42275     return SDValue();
42276 
42277   // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
42278   // legalization destroys the v4i32 type.
42279   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
42280     if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
42281       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
42282                       DAG.getBitcast(MVT::v4f32, V));
42283       return DAG.getZExtOrTrunc(V, DL, VT);
42284     }
42285   }
42286 
42287   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
42288   // movmskb even with avx512. This will be better than truncating to vXi1 and
42289   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
42290   // vpcmpeqb/vpcmpgtb.
42291   bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
42292                       (Src.getOperand(0).getValueType() == MVT::v16i8 ||
42293                        Src.getOperand(0).getValueType() == MVT::v32i8 ||
42294                        Src.getOperand(0).getValueType() == MVT::v64i8);
42295 
42296   // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
42297   // directly with vpmovmskb/vmovmskps/vmovmskpd.
42298   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
42299       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
42300       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
42301     EVT CmpVT = Src.getOperand(0).getValueType();
42302     EVT EltVT = CmpVT.getVectorElementType();
42303     if (CmpVT.getSizeInBits() <= 256 &&
42304         (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
42305       PreferMovMsk = true;
42306   }
42307 
42308   // With AVX512 vxi1 types are legal and we prefer using k-regs.
42309   // MOVMSK is supported in SSE2 or later.
42310   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
42311     return SDValue();
42312 
42313   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
42314   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
42315   // v8i16 and v16i16.
42316   // For these two cases, we can shuffle the upper element bytes to a
42317   // consecutive sequence at the start of the vector and treat the results as
42318   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
42319   // for v16i16 this is not the case, because the shuffle is expensive, so we
42320   // avoid sign-extending to this type entirely.
42321   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
42322   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
42323   MVT SExtVT;
42324   bool PropagateSExt = false;
42325   switch (SrcVT.getSimpleVT().SimpleTy) {
42326   default:
42327     return SDValue();
42328   case MVT::v2i1:
42329     SExtVT = MVT::v2i64;
42330     break;
42331   case MVT::v4i1:
42332     SExtVT = MVT::v4i32;
42333     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
42334     // sign-extend to a 256-bit operation to avoid truncation.
42335     if (Subtarget.hasAVX() &&
42336         checkBitcastSrcVectorSize(Src, 256, Subtarget.hasAVX2())) {
42337       SExtVT = MVT::v4i64;
42338       PropagateSExt = true;
42339     }
42340     break;
42341   case MVT::v8i1:
42342     SExtVT = MVT::v8i16;
42343     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
42344     // sign-extend to a 256-bit operation to match the compare.
42345     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
42346     // 256-bit because the shuffle is cheaper than sign extending the result of
42347     // the compare.
42348     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256, true) ||
42349                                checkBitcastSrcVectorSize(Src, 512, true))) {
42350       SExtVT = MVT::v8i32;
42351       PropagateSExt = true;
42352     }
42353     break;
42354   case MVT::v16i1:
42355     SExtVT = MVT::v16i8;
42356     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
42357     // it is not profitable to sign-extend to 256-bit because this will
42358     // require an extra cross-lane shuffle which is more expensive than
42359     // truncating the result of the compare to 128-bits.
42360     break;
42361   case MVT::v32i1:
42362     SExtVT = MVT::v32i8;
42363     break;
42364   case MVT::v64i1:
42365     // If we have AVX512F, but not AVX512BW and the input is truncated from
42366     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
42367     if (Subtarget.hasAVX512()) {
42368       if (Subtarget.hasBWI())
42369         return SDValue();
42370       SExtVT = MVT::v64i8;
42371       break;
42372     }
42373     // Split if this is a <64 x i8> comparison result.
42374     if (checkBitcastSrcVectorSize(Src, 512, false)) {
42375       SExtVT = MVT::v64i8;
42376       break;
42377     }
42378     return SDValue();
42379   };
42380 
42381   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
42382                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
42383 
42384   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
42385     V = getPMOVMSKB(DL, V, DAG, Subtarget);
42386   } else {
42387     if (SExtVT == MVT::v8i16)
42388       V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
42389                       DAG.getUNDEF(MVT::v8i16));
42390     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
42391   }
42392 
42393   EVT IntVT =
42394       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
42395   V = DAG.getZExtOrTrunc(V, DL, IntVT);
42396   return DAG.getBitcast(VT, V);
42397 }
42398 
42399 // Convert a vXi1 constant build vector to the same width scalar integer.
42400 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
42401   EVT SrcVT = Op.getValueType();
42402   assert(SrcVT.getVectorElementType() == MVT::i1 &&
42403          "Expected a vXi1 vector");
42404   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
42405          "Expected a constant build vector");
42406 
42407   APInt Imm(SrcVT.getVectorNumElements(), 0);
42408   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
42409     SDValue In = Op.getOperand(Idx);
42410     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
42411       Imm.setBit(Idx);
42412   }
42413   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
42414   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
42415 }
42416 
42417 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
42418                                            TargetLowering::DAGCombinerInfo &DCI,
42419                                            const X86Subtarget &Subtarget) {
42420   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
42421 
42422   if (!DCI.isBeforeLegalizeOps())
42423     return SDValue();
42424 
42425   // Only do this if we have k-registers.
42426   if (!Subtarget.hasAVX512())
42427     return SDValue();
42428 
42429   EVT DstVT = N->getValueType(0);
42430   SDValue Op = N->getOperand(0);
42431   EVT SrcVT = Op.getValueType();
42432 
42433   if (!Op.hasOneUse())
42434     return SDValue();
42435 
42436   // Look for logic ops.
42437   if (Op.getOpcode() != ISD::AND &&
42438       Op.getOpcode() != ISD::OR &&
42439       Op.getOpcode() != ISD::XOR)
42440     return SDValue();
42441 
42442   // Make sure we have a bitcast between mask registers and a scalar type.
42443   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
42444         DstVT.isScalarInteger()) &&
42445       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
42446         SrcVT.isScalarInteger()))
42447     return SDValue();
42448 
42449   SDValue LHS = Op.getOperand(0);
42450   SDValue RHS = Op.getOperand(1);
42451 
42452   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
42453       LHS.getOperand(0).getValueType() == DstVT)
42454     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
42455                        DAG.getBitcast(DstVT, RHS));
42456 
42457   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
42458       RHS.getOperand(0).getValueType() == DstVT)
42459     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
42460                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
42461 
42462   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
42463   // Most of these have to move a constant from the scalar domain anyway.
42464   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
42465     RHS = combinevXi1ConstantToInteger(RHS, DAG);
42466     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
42467                        DAG.getBitcast(DstVT, LHS), RHS);
42468   }
42469 
42470   return SDValue();
42471 }
42472 
42473 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
42474                                     const X86Subtarget &Subtarget) {
42475   SDLoc DL(BV);
42476   unsigned NumElts = BV->getNumOperands();
42477   SDValue Splat = BV->getSplatValue();
42478 
42479   // Build MMX element from integer GPR or SSE float values.
42480   auto CreateMMXElement = [&](SDValue V) {
42481     if (V.isUndef())
42482       return DAG.getUNDEF(MVT::x86mmx);
42483     if (V.getValueType().isFloatingPoint()) {
42484       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
42485         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
42486         V = DAG.getBitcast(MVT::v2i64, V);
42487         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
42488       }
42489       V = DAG.getBitcast(MVT::i32, V);
42490     } else {
42491       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
42492     }
42493     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
42494   };
42495 
42496   // Convert build vector ops to MMX data in the bottom elements.
42497   SmallVector<SDValue, 8> Ops;
42498 
42499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42500 
42501   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
42502   if (Splat) {
42503     if (Splat.isUndef())
42504       return DAG.getUNDEF(MVT::x86mmx);
42505 
42506     Splat = CreateMMXElement(Splat);
42507 
42508     if (Subtarget.hasSSE1()) {
42509       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
42510       if (NumElts == 8)
42511         Splat = DAG.getNode(
42512             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
42513             DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
42514                                   TLI.getPointerTy(DAG.getDataLayout())),
42515             Splat, Splat);
42516 
42517       // Use PSHUFW to repeat 16-bit elements.
42518       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
42519       return DAG.getNode(
42520           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
42521           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
42522                                 TLI.getPointerTy(DAG.getDataLayout())),
42523           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
42524     }
42525     Ops.append(NumElts, Splat);
42526   } else {
42527     for (unsigned i = 0; i != NumElts; ++i)
42528       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
42529   }
42530 
42531   // Use tree of PUNPCKLs to build up general MMX vector.
42532   while (Ops.size() > 1) {
42533     unsigned NumOps = Ops.size();
42534     unsigned IntrinOp =
42535         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
42536                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
42537                                     : Intrinsic::x86_mmx_punpcklbw));
42538     SDValue Intrin = DAG.getTargetConstant(
42539         IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
42540     for (unsigned i = 0; i != NumOps; i += 2)
42541       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
42542                                Ops[i], Ops[i + 1]);
42543     Ops.resize(NumOps / 2);
42544   }
42545 
42546   return Ops[0];
42547 }
42548 
42549 // Recursive function that attempts to find if a bool vector node was originally
42550 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
42551 // integer. If so, replace the scalar ops with bool vector equivalents back down
42552 // the chain.
42553 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
42554                                           SelectionDAG &DAG,
42555                                           const X86Subtarget &Subtarget) {
42556   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42557   unsigned Opc = V.getOpcode();
42558   switch (Opc) {
42559   case ISD::BITCAST: {
42560     // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
42561     SDValue Src = V.getOperand(0);
42562     EVT SrcVT = Src.getValueType();
42563     if (SrcVT.isVector() || SrcVT.isFloatingPoint())
42564       return DAG.getBitcast(VT, Src);
42565     break;
42566   }
42567   case ISD::TRUNCATE: {
42568     // If we find a suitable source, a truncated scalar becomes a subvector.
42569     SDValue Src = V.getOperand(0);
42570     EVT NewSrcVT =
42571         EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
42572     if (TLI.isTypeLegal(NewSrcVT))
42573       if (SDValue N0 =
42574               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
42575         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
42576                            DAG.getIntPtrConstant(0, DL));
42577     break;
42578   }
42579   case ISD::ANY_EXTEND:
42580   case ISD::ZERO_EXTEND: {
42581     // If we find a suitable source, an extended scalar becomes a subvector.
42582     SDValue Src = V.getOperand(0);
42583     EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
42584                                     Src.getScalarValueSizeInBits());
42585     if (TLI.isTypeLegal(NewSrcVT))
42586       if (SDValue N0 =
42587               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
42588         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
42589                            Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
42590                                                   : DAG.getConstant(0, DL, VT),
42591                            N0, DAG.getIntPtrConstant(0, DL));
42592     break;
42593   }
42594   case ISD::OR: {
42595     // If we find suitable sources, we can just move an OR to the vector domain.
42596     SDValue Src0 = V.getOperand(0);
42597     SDValue Src1 = V.getOperand(1);
42598     if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
42599       if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
42600         return DAG.getNode(Opc, DL, VT, N0, N1);
42601     break;
42602   }
42603   case ISD::SHL: {
42604     // If we find a suitable source, a SHL becomes a KSHIFTL.
42605     SDValue Src0 = V.getOperand(0);
42606     if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
42607         ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
42608       break;
42609 
42610     if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
42611       if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
42612         return DAG.getNode(
42613             X86ISD::KSHIFTL, DL, VT, N0,
42614             DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
42615     break;
42616   }
42617   }
42618   return SDValue();
42619 }
42620 
42621 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
42622                               TargetLowering::DAGCombinerInfo &DCI,
42623                               const X86Subtarget &Subtarget) {
42624   SDValue N0 = N->getOperand(0);
42625   EVT VT = N->getValueType(0);
42626   EVT SrcVT = N0.getValueType();
42627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42628 
42629   // Try to match patterns such as
42630   // (i16 bitcast (v16i1 x))
42631   // ->
42632   // (i16 movmsk (16i8 sext (v16i1 x)))
42633   // before the setcc result is scalarized on subtargets that don't have legal
42634   // vxi1 types.
42635   if (DCI.isBeforeLegalize()) {
42636     SDLoc dl(N);
42637     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
42638       return V;
42639 
42640     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
42641     // type, widen both sides to avoid a trip through memory.
42642     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
42643         Subtarget.hasAVX512()) {
42644       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
42645       N0 = DAG.getBitcast(MVT::v8i1, N0);
42646       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
42647                          DAG.getIntPtrConstant(0, dl));
42648     }
42649 
42650     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
42651     // type, widen both sides to avoid a trip through memory.
42652     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
42653         Subtarget.hasAVX512()) {
42654       // Use zeros for the widening if we already have some zeroes. This can
42655       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
42656       // stream of this.
42657       // FIXME: It might make sense to detect a concat_vectors with a mix of
42658       // zeroes and undef and turn it into insert_subvector for i1 vectors as
42659       // a separate combine. What we can't do is canonicalize the operands of
42660       // such a concat or we'll get into a loop with SimplifyDemandedBits.
42661       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
42662         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
42663         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
42664           SrcVT = LastOp.getValueType();
42665           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
42666           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
42667           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
42668           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
42669           N0 = DAG.getBitcast(MVT::i8, N0);
42670           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
42671         }
42672       }
42673 
42674       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
42675       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
42676       Ops[0] = N0;
42677       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
42678       N0 = DAG.getBitcast(MVT::i8, N0);
42679       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
42680     }
42681   } else {
42682     // If we're bitcasting from iX to vXi1, see if the integer originally
42683     // began as a vXi1 and whether we can remove the bitcast entirely.
42684     if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
42685         SrcVT.isScalarInteger() && TLI.isTypeLegal(VT)) {
42686       if (SDValue V =
42687               combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
42688         return V;
42689     }
42690   }
42691 
42692   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
42693   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
42694   // due to insert_subvector legalization on KNL. By promoting the copy to i16
42695   // we can help with known bits propagation from the vXi1 domain to the
42696   // scalar domain.
42697   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
42698       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42699       N0.getOperand(0).getValueType() == MVT::v16i1 &&
42700       isNullConstant(N0.getOperand(1)))
42701     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
42702                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
42703 
42704   // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
42705   // and the vbroadcast_load are both integer or both fp. In some cases this
42706   // will remove the bitcast entirely.
42707   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
42708        VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
42709     auto *BCast = cast<MemIntrinsicSDNode>(N0);
42710     unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
42711     unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
42712     // Don't swap i8/i16 since don't have fp types that size.
42713     if (MemSize >= 32) {
42714       MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
42715                                        : MVT::getIntegerVT(MemSize);
42716       MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
42717                                         : MVT::getIntegerVT(SrcVTSize);
42718       LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
42719 
42720       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
42721       SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
42722       SDValue ResNode =
42723           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
42724                                   MemVT, BCast->getMemOperand());
42725       DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
42726       return DAG.getBitcast(VT, ResNode);
42727     }
42728   }
42729 
42730   // Since MMX types are special and don't usually play with other vector types,
42731   // it's better to handle them early to be sure we emit efficient code by
42732   // avoiding store-load conversions.
42733   if (VT == MVT::x86mmx) {
42734     // Detect MMX constant vectors.
42735     APInt UndefElts;
42736     SmallVector<APInt, 1> EltBits;
42737     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
42738       SDLoc DL(N0);
42739       // Handle zero-extension of i32 with MOVD.
42740       if (EltBits[0].countLeadingZeros() >= 32)
42741         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
42742                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
42743       // Else, bitcast to a double.
42744       // TODO - investigate supporting sext 32-bit immediates on x86_64.
42745       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
42746       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
42747     }
42748 
42749     // Detect bitcasts to x86mmx low word.
42750     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
42751         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
42752         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
42753       bool LowUndef = true, AllUndefOrZero = true;
42754       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
42755         SDValue Op = N0.getOperand(i);
42756         LowUndef &= Op.isUndef() || (i >= e/2);
42757         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
42758       }
42759       if (AllUndefOrZero) {
42760         SDValue N00 = N0.getOperand(0);
42761         SDLoc dl(N00);
42762         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
42763                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
42764         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
42765       }
42766     }
42767 
42768     // Detect bitcasts of 64-bit build vectors and convert to a
42769     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
42770     // lowest element.
42771     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
42772         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
42773          SrcVT == MVT::v8i8))
42774       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
42775 
42776     // Detect bitcasts between element or subvector extraction to x86mmx.
42777     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
42778          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
42779         isNullConstant(N0.getOperand(1))) {
42780       SDValue N00 = N0.getOperand(0);
42781       if (N00.getValueType().is128BitVector())
42782         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
42783                            DAG.getBitcast(MVT::v2i64, N00));
42784     }
42785 
42786     // Detect bitcasts from FP_TO_SINT to x86mmx.
42787     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
42788       SDLoc DL(N0);
42789       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
42790                                 DAG.getUNDEF(MVT::v2i32));
42791       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
42792                          DAG.getBitcast(MVT::v2i64, Res));
42793     }
42794   }
42795 
42796   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
42797   // most of these to scalar anyway.
42798   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
42799       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
42800       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
42801     return combinevXi1ConstantToInteger(N0, DAG);
42802   }
42803 
42804   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
42805       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
42806       isa<ConstantSDNode>(N0)) {
42807     auto *C = cast<ConstantSDNode>(N0);
42808     if (C->isAllOnes())
42809       return DAG.getConstant(1, SDLoc(N0), VT);
42810     if (C->isZero())
42811       return DAG.getConstant(0, SDLoc(N0), VT);
42812   }
42813 
42814   // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
42815   // Turn it into a sign bit compare that produces a k-register. This avoids
42816   // a trip through a GPR.
42817   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
42818       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
42819       isPowerOf2_32(VT.getVectorNumElements())) {
42820     unsigned NumElts = VT.getVectorNumElements();
42821     SDValue Src = N0;
42822 
42823     // Peek through truncate.
42824     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
42825       Src = N0.getOperand(0);
42826 
42827     if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
42828       SDValue MovmskIn = Src.getOperand(0);
42829       MVT MovmskVT = MovmskIn.getSimpleValueType();
42830       unsigned MovMskElts = MovmskVT.getVectorNumElements();
42831 
42832       // We allow extra bits of the movmsk to be used since they are known zero.
42833       // We can't convert a VPMOVMSKB without avx512bw.
42834       if (MovMskElts <= NumElts &&
42835           (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
42836         EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
42837         MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
42838         SDLoc dl(N);
42839         MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
42840         SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
42841                                    DAG.getConstant(0, dl, IntVT), ISD::SETLT);
42842         if (EVT(CmpVT) == VT)
42843           return Cmp;
42844 
42845         // Pad with zeroes up to original VT to replace the zeroes that were
42846         // being used from the MOVMSK.
42847         unsigned NumConcats = NumElts / MovMskElts;
42848         SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
42849         Ops[0] = Cmp;
42850         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
42851       }
42852     }
42853   }
42854 
42855   // Try to remove bitcasts from input and output of mask arithmetic to
42856   // remove GPR<->K-register crossings.
42857   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
42858     return V;
42859 
42860   // Convert a bitcasted integer logic operation that has one bitcasted
42861   // floating-point operand into a floating-point logic operation. This may
42862   // create a load of a constant, but that is cheaper than materializing the
42863   // constant in an integer register and transferring it to an SSE register or
42864   // transferring the SSE operand to integer register and back.
42865   unsigned FPOpcode;
42866   switch (N0.getOpcode()) {
42867     case ISD::AND: FPOpcode = X86ISD::FAND; break;
42868     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
42869     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
42870     default: return SDValue();
42871   }
42872 
42873   // Check if we have a bitcast from another integer type as well.
42874   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
42875         (Subtarget.hasSSE2() && VT == MVT::f64) ||
42876         (Subtarget.hasFP16() && VT == MVT::f16) ||
42877         (Subtarget.hasSSE2() && VT.isInteger() && VT.isVector() &&
42878          TLI.isTypeLegal(VT))))
42879     return SDValue();
42880 
42881   SDValue LogicOp0 = N0.getOperand(0);
42882   SDValue LogicOp1 = N0.getOperand(1);
42883   SDLoc DL0(N0);
42884 
42885   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
42886   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
42887       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).hasOneUse() &&
42888       LogicOp0.getOperand(0).getValueType() == VT &&
42889       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
42890     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
42891     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
42892     return DAG.getNode(Opcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
42893   }
42894   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
42895   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
42896       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).hasOneUse() &&
42897       LogicOp1.getOperand(0).getValueType() == VT &&
42898       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
42899     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
42900     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
42901     return DAG.getNode(Opcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
42902   }
42903 
42904   return SDValue();
42905 }
42906 
42907 // (mul (zext a), (sext, b))
42908 static bool detectExtMul(SelectionDAG &DAG, const SDValue &Mul, SDValue &Op0,
42909                          SDValue &Op1) {
42910   Op0 = Mul.getOperand(0);
42911   Op1 = Mul.getOperand(1);
42912 
42913   // The operand1 should be signed extend
42914   if (Op0.getOpcode() == ISD::SIGN_EXTEND)
42915     std::swap(Op0, Op1);
42916 
42917   auto IsFreeTruncation = [](SDValue &Op) -> bool {
42918     if ((Op.getOpcode() == ISD::ZERO_EXTEND ||
42919          Op.getOpcode() == ISD::SIGN_EXTEND) &&
42920         Op.getOperand(0).getScalarValueSizeInBits() <= 8)
42921       return true;
42922 
42923     auto *BV = dyn_cast<BuildVectorSDNode>(Op);
42924     return (BV && BV->isConstant());
42925   };
42926 
42927   // (dpbusd (zext a), (sext, b)). Since the first operand should be unsigned
42928   // value, we need to check Op0 is zero extended value. Op1 should be signed
42929   // value, so we just check the signed bits.
42930   if ((IsFreeTruncation(Op0) &&
42931        DAG.computeKnownBits(Op0).countMaxActiveBits() <= 8) &&
42932       (IsFreeTruncation(Op1) && DAG.ComputeMaxSignificantBits(Op1) <= 8))
42933     return true;
42934 
42935   return false;
42936 }
42937 
42938 // Given a ABS node, detect the following pattern:
42939 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
42940 // This is useful as it is the input into a SAD pattern.
42941 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
42942   SDValue AbsOp1 = Abs->getOperand(0);
42943   if (AbsOp1.getOpcode() != ISD::SUB)
42944     return false;
42945 
42946   Op0 = AbsOp1.getOperand(0);
42947   Op1 = AbsOp1.getOperand(1);
42948 
42949   // Check if the operands of the sub are zero-extended from vectors of i8.
42950   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
42951       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
42952       Op1.getOpcode() != ISD::ZERO_EXTEND ||
42953       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
42954     return false;
42955 
42956   return true;
42957 }
42958 
42959 static SDValue createVPDPBUSD(SelectionDAG &DAG, SDValue LHS, SDValue RHS,
42960                               unsigned &LogBias, const SDLoc &DL,
42961                               const X86Subtarget &Subtarget) {
42962   // Extend or truncate to MVT::i8 first.
42963   MVT Vi8VT =
42964       MVT::getVectorVT(MVT::i8, LHS.getValueType().getVectorElementCount());
42965   LHS = DAG.getZExtOrTrunc(LHS, DL, Vi8VT);
42966   RHS = DAG.getSExtOrTrunc(RHS, DL, Vi8VT);
42967 
42968   // VPDPBUSD(<16 x i32>C, <16 x i8>A, <16 x i8>B). For each dst element
42969   // C[0] = C[0] + A[0]B[0] + A[1]B[1] + A[2]B[2] + A[3]B[3].
42970   // The src A, B element type is i8, but the dst C element type is i32.
42971   // When we calculate the reduce stage, we use src vector type vXi8 for it
42972   // so we need logbias 2 to avoid extra 2 stages.
42973   LogBias = 2;
42974 
42975   unsigned RegSize = std::max(128u, (unsigned)Vi8VT.getSizeInBits());
42976   if (Subtarget.hasVNNI() && !Subtarget.hasVLX())
42977     RegSize = std::max(512u, RegSize);
42978 
42979   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
42980   // fill in the missing vector elements with 0.
42981   unsigned NumConcat = RegSize / Vi8VT.getSizeInBits();
42982   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, Vi8VT));
42983   Ops[0] = LHS;
42984   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
42985   SDValue DpOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
42986   Ops[0] = RHS;
42987   SDValue DpOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
42988 
42989   // Actually build the DotProduct, split as 256/512 bits for
42990   // AVXVNNI/AVX512VNNI.
42991   auto DpBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42992                        ArrayRef<SDValue> Ops) {
42993     MVT VT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
42994     return DAG.getNode(X86ISD::VPDPBUSD, DL, VT, Ops);
42995   };
42996   MVT DpVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
42997   SDValue Zero = DAG.getConstant(0, DL, DpVT);
42998 
42999   return SplitOpsAndApply(DAG, Subtarget, DL, DpVT, {Zero, DpOp0, DpOp1},
43000                           DpBuilder, false);
43001 }
43002 
43003 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
43004 // to these zexts.
43005 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
43006                             const SDValue &Zext1, const SDLoc &DL,
43007                             const X86Subtarget &Subtarget) {
43008   // Find the appropriate width for the PSADBW.
43009   EVT InVT = Zext0.getOperand(0).getValueType();
43010   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
43011 
43012   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
43013   // fill in the missing vector elements with 0.
43014   unsigned NumConcat = RegSize / InVT.getSizeInBits();
43015   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
43016   Ops[0] = Zext0.getOperand(0);
43017   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
43018   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
43019   Ops[0] = Zext1.getOperand(0);
43020   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
43021 
43022   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
43023   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43024                           ArrayRef<SDValue> Ops) {
43025     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
43026     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
43027   };
43028   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
43029   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
43030                           PSADBWBuilder);
43031 }
43032 
43033 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
43034 // PHMINPOSUW.
43035 static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
43036                                       const X86Subtarget &Subtarget) {
43037   // Bail without SSE41.
43038   if (!Subtarget.hasSSE41())
43039     return SDValue();
43040 
43041   EVT ExtractVT = Extract->getValueType(0);
43042   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
43043     return SDValue();
43044 
43045   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
43046   ISD::NodeType BinOp;
43047   SDValue Src = DAG.matchBinOpReduction(
43048       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
43049   if (!Src)
43050     return SDValue();
43051 
43052   EVT SrcVT = Src.getValueType();
43053   EVT SrcSVT = SrcVT.getScalarType();
43054   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
43055     return SDValue();
43056 
43057   SDLoc DL(Extract);
43058   SDValue MinPos = Src;
43059 
43060   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
43061   while (SrcVT.getSizeInBits() > 128) {
43062     SDValue Lo, Hi;
43063     std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
43064     SrcVT = Lo.getValueType();
43065     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
43066   }
43067   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
43068           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
43069          "Unexpected value type");
43070 
43071   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
43072   // to flip the value accordingly.
43073   SDValue Mask;
43074   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
43075   if (BinOp == ISD::SMAX)
43076     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
43077   else if (BinOp == ISD::SMIN)
43078     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
43079   else if (BinOp == ISD::UMAX)
43080     Mask = DAG.getAllOnesConstant(DL, SrcVT);
43081 
43082   if (Mask)
43083     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
43084 
43085   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
43086   // shuffling each upper element down and insert zeros. This means that the
43087   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
43088   // ready for the PHMINPOS.
43089   if (ExtractVT == MVT::i8) {
43090     SDValue Upper = DAG.getVectorShuffle(
43091         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
43092         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
43093     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
43094   }
43095 
43096   // Perform the PHMINPOS on a v8i16 vector,
43097   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
43098   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
43099   MinPos = DAG.getBitcast(SrcVT, MinPos);
43100 
43101   if (Mask)
43102     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
43103 
43104   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
43105                      DAG.getIntPtrConstant(0, DL));
43106 }
43107 
43108 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
43109 static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
43110                                          const X86Subtarget &Subtarget) {
43111   // Bail without SSE2.
43112   if (!Subtarget.hasSSE2())
43113     return SDValue();
43114 
43115   EVT ExtractVT = Extract->getValueType(0);
43116   unsigned BitWidth = ExtractVT.getSizeInBits();
43117   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
43118       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
43119     return SDValue();
43120 
43121   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
43122   ISD::NodeType BinOp;
43123   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
43124   if (!Match && ExtractVT == MVT::i1)
43125     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
43126   if (!Match)
43127     return SDValue();
43128 
43129   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
43130   // which we can't support here for now.
43131   if (Match.getScalarValueSizeInBits() != BitWidth)
43132     return SDValue();
43133 
43134   SDValue Movmsk;
43135   SDLoc DL(Extract);
43136   EVT MatchVT = Match.getValueType();
43137   unsigned NumElts = MatchVT.getVectorNumElements();
43138   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
43139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43140 
43141   if (ExtractVT == MVT::i1) {
43142     // Special case for (pre-legalization) vXi1 reductions.
43143     if (NumElts > 64 || !isPowerOf2_32(NumElts))
43144       return SDValue();
43145     if (TLI.isTypeLegal(MatchVT)) {
43146       // If this is a legal AVX512 predicate type then we can just bitcast.
43147       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
43148       Movmsk = DAG.getBitcast(MovmskVT, Match);
43149     } else {
43150       // For all_of(setcc(x,y,eq)) - use PMOVMSKB(PCMPEQB()).
43151       if (BinOp == ISD::AND && Match.getOpcode() == ISD::SETCC &&
43152           cast<CondCodeSDNode>(Match.getOperand(2))->get() ==
43153               ISD::CondCode::SETEQ) {
43154         EVT VecSVT = Match.getOperand(0).getValueType().getScalarType();
43155         if (VecSVT != MVT::i8) {
43156           NumElts *= VecSVT.getSizeInBits() / 8;
43157           EVT CmpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, NumElts);
43158           MatchVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
43159           Match = DAG.getSetCC(
43160               DL, MatchVT, DAG.getBitcast(CmpVT, Match.getOperand(0)),
43161               DAG.getBitcast(CmpVT, Match.getOperand(1)), ISD::CondCode::SETEQ);
43162         }
43163       }
43164 
43165       // Use combineBitcastvxi1 to create the MOVMSK.
43166       while (NumElts > MaxElts) {
43167         SDValue Lo, Hi;
43168         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
43169         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
43170         NumElts /= 2;
43171       }
43172       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
43173       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
43174     }
43175     if (!Movmsk)
43176       return SDValue();
43177     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
43178   } else {
43179     // FIXME: Better handling of k-registers or 512-bit vectors?
43180     unsigned MatchSizeInBits = Match.getValueSizeInBits();
43181     if (!(MatchSizeInBits == 128 ||
43182           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
43183       return SDValue();
43184 
43185     // Make sure this isn't a vector of 1 element. The perf win from using
43186     // MOVMSK diminishes with less elements in the reduction, but it is
43187     // generally better to get the comparison over to the GPRs as soon as
43188     // possible to reduce the number of vector ops.
43189     if (Match.getValueType().getVectorNumElements() < 2)
43190       return SDValue();
43191 
43192     // Check that we are extracting a reduction of all sign bits.
43193     if (DAG.ComputeNumSignBits(Match) != BitWidth)
43194       return SDValue();
43195 
43196     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
43197       SDValue Lo, Hi;
43198       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
43199       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
43200       MatchSizeInBits = Match.getValueSizeInBits();
43201     }
43202 
43203     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
43204     MVT MaskSrcVT;
43205     if (64 == BitWidth || 32 == BitWidth)
43206       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
43207                                    MatchSizeInBits / BitWidth);
43208     else
43209       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
43210 
43211     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
43212     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
43213     NumElts = MaskSrcVT.getVectorNumElements();
43214   }
43215   assert((NumElts <= 32 || NumElts == 64) &&
43216          "Not expecting more than 64 elements");
43217 
43218   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
43219   if (BinOp == ISD::XOR) {
43220     // parity -> (PARITY(MOVMSK X))
43221     SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
43222     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
43223   }
43224 
43225   SDValue CmpC;
43226   ISD::CondCode CondCode;
43227   if (BinOp == ISD::OR) {
43228     // any_of -> MOVMSK != 0
43229     CmpC = DAG.getConstant(0, DL, CmpVT);
43230     CondCode = ISD::CondCode::SETNE;
43231   } else {
43232     // all_of -> MOVMSK == ((1 << NumElts) - 1)
43233     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
43234                            DL, CmpVT);
43235     CondCode = ISD::CondCode::SETEQ;
43236   }
43237 
43238   // The setcc produces an i8 of 0/1, so extend that to the result width and
43239   // negate to get the final 0/-1 mask value.
43240   EVT SetccVT =
43241       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
43242   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
43243   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
43244   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
43245   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
43246 }
43247 
43248 static SDValue combineVPDPBUSDPattern(SDNode *Extract, SelectionDAG &DAG,
43249                                       const X86Subtarget &Subtarget) {
43250   if (!Subtarget.hasVNNI() && !Subtarget.hasAVXVNNI())
43251     return SDValue();
43252 
43253   EVT ExtractVT = Extract->getValueType(0);
43254   // Verify the type we're extracting is i32, as the output element type of
43255   // vpdpbusd is i32.
43256   if (ExtractVT != MVT::i32)
43257     return SDValue();
43258 
43259   EVT VT = Extract->getOperand(0).getValueType();
43260   if (!isPowerOf2_32(VT.getVectorNumElements()))
43261     return SDValue();
43262 
43263   // Match shuffle + add pyramid.
43264   ISD::NodeType BinOp;
43265   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
43266 
43267   // We can't combine to vpdpbusd for zext, because each of the 4 multiplies
43268   // done by vpdpbusd compute a signed 16-bit product that will be sign extended
43269   // before adding into the accumulator.
43270   // TODO:
43271   // We also need to verify that the multiply has at least 2x the number of bits
43272   // of the input. We shouldn't match
43273   // (sign_extend (mul (vXi9 (zext (vXi8 X))), (vXi9 (zext (vXi8 Y)))).
43274   // if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND))
43275   //   Root = Root.getOperand(0);
43276 
43277   // If there was a match, we want Root to be a mul.
43278   if (!Root || Root.getOpcode() != ISD::MUL)
43279     return SDValue();
43280 
43281   // Check whether we have an extend and mul pattern
43282   SDValue LHS, RHS;
43283   if (!detectExtMul(DAG, Root, LHS, RHS))
43284     return SDValue();
43285 
43286   // Create the dot product instruction.
43287   SDLoc DL(Extract);
43288   unsigned StageBias;
43289   SDValue DP = createVPDPBUSD(DAG, LHS, RHS, StageBias, DL, Subtarget);
43290 
43291   // If the original vector was wider than 4 elements, sum over the results
43292   // in the DP vector.
43293   unsigned Stages = Log2_32(VT.getVectorNumElements());
43294   EVT DpVT = DP.getValueType();
43295 
43296   if (Stages > StageBias) {
43297     unsigned DpElems = DpVT.getVectorNumElements();
43298 
43299     for (unsigned i = Stages - StageBias; i > 0; --i) {
43300       SmallVector<int, 16> Mask(DpElems, -1);
43301       for (unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
43302         Mask[j] = MaskEnd + j;
43303 
43304       SDValue Shuffle =
43305           DAG.getVectorShuffle(DpVT, DL, DP, DAG.getUNDEF(DpVT), Mask);
43306       DP = DAG.getNode(ISD::ADD, DL, DpVT, DP, Shuffle);
43307     }
43308   }
43309 
43310   // Return the lowest ExtractSizeInBits bits.
43311   EVT ResVT =
43312       EVT::getVectorVT(*DAG.getContext(), ExtractVT,
43313                        DpVT.getSizeInBits() / ExtractVT.getSizeInBits());
43314   DP = DAG.getBitcast(ResVT, DP);
43315   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, DP,
43316                      Extract->getOperand(1));
43317 }
43318 
43319 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
43320                                       const X86Subtarget &Subtarget) {
43321   // PSADBW is only supported on SSE2 and up.
43322   if (!Subtarget.hasSSE2())
43323     return SDValue();
43324 
43325   EVT ExtractVT = Extract->getValueType(0);
43326   // Verify the type we're extracting is either i32 or i64.
43327   // FIXME: Could support other types, but this is what we have coverage for.
43328   if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
43329     return SDValue();
43330 
43331   EVT VT = Extract->getOperand(0).getValueType();
43332   if (!isPowerOf2_32(VT.getVectorNumElements()))
43333     return SDValue();
43334 
43335   // Match shuffle + add pyramid.
43336   ISD::NodeType BinOp;
43337   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
43338 
43339   // The operand is expected to be zero extended from i8
43340   // (verified in detectZextAbsDiff).
43341   // In order to convert to i64 and above, additional any/zero/sign
43342   // extend is expected.
43343   // The zero extend from 32 bit has no mathematical effect on the result.
43344   // Also the sign extend is basically zero extend
43345   // (extends the sign bit which is zero).
43346   // So it is correct to skip the sign/zero extend instruction.
43347   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
43348                Root.getOpcode() == ISD::ZERO_EXTEND ||
43349                Root.getOpcode() == ISD::ANY_EXTEND))
43350     Root = Root.getOperand(0);
43351 
43352   // If there was a match, we want Root to be a select that is the root of an
43353   // abs-diff pattern.
43354   if (!Root || Root.getOpcode() != ISD::ABS)
43355     return SDValue();
43356 
43357   // Check whether we have an abs-diff pattern feeding into the select.
43358   SDValue Zext0, Zext1;
43359   if (!detectZextAbsDiff(Root, Zext0, Zext1))
43360     return SDValue();
43361 
43362   // Create the SAD instruction.
43363   SDLoc DL(Extract);
43364   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
43365 
43366   // If the original vector was wider than 8 elements, sum over the results
43367   // in the SAD vector.
43368   unsigned Stages = Log2_32(VT.getVectorNumElements());
43369   EVT SadVT = SAD.getValueType();
43370   if (Stages > 3) {
43371     unsigned SadElems = SadVT.getVectorNumElements();
43372 
43373     for(unsigned i = Stages - 3; i > 0; --i) {
43374       SmallVector<int, 16> Mask(SadElems, -1);
43375       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
43376         Mask[j] = MaskEnd + j;
43377 
43378       SDValue Shuffle =
43379           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
43380       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
43381     }
43382   }
43383 
43384   unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
43385   // Return the lowest ExtractSizeInBits bits.
43386   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
43387                                SadVT.getSizeInBits() / ExtractSizeInBits);
43388   SAD = DAG.getBitcast(ResVT, SAD);
43389   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
43390                      Extract->getOperand(1));
43391 }
43392 
43393 // Attempt to peek through a target shuffle and extract the scalar from the
43394 // source.
43395 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
43396                                          TargetLowering::DAGCombinerInfo &DCI,
43397                                          const X86Subtarget &Subtarget) {
43398   if (DCI.isBeforeLegalizeOps())
43399     return SDValue();
43400 
43401   SDLoc dl(N);
43402   SDValue Src = N->getOperand(0);
43403   SDValue Idx = N->getOperand(1);
43404 
43405   EVT VT = N->getValueType(0);
43406   EVT SrcVT = Src.getValueType();
43407   EVT SrcSVT = SrcVT.getVectorElementType();
43408   unsigned SrcEltBits = SrcSVT.getSizeInBits();
43409   unsigned NumSrcElts = SrcVT.getVectorNumElements();
43410 
43411   // Don't attempt this for boolean mask vectors or unknown extraction indices.
43412   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
43413     return SDValue();
43414 
43415   const APInt &IdxC = N->getConstantOperandAPInt(1);
43416   if (IdxC.uge(NumSrcElts))
43417     return SDValue();
43418 
43419   SDValue SrcBC = peekThroughBitcasts(Src);
43420 
43421   // Handle extract(bitcast(broadcast(scalar_value))).
43422   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
43423     SDValue SrcOp = SrcBC.getOperand(0);
43424     EVT SrcOpVT = SrcOp.getValueType();
43425     if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
43426         (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
43427       unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
43428       unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
43429       // TODO support non-zero offsets.
43430       if (Offset == 0) {
43431         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
43432         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
43433         return SrcOp;
43434       }
43435     }
43436   }
43437 
43438   // If we're extracting a single element from a broadcast load and there are
43439   // no other users, just create a single load.
43440   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
43441     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
43442     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
43443     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
43444         VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
43445       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
43446                                  MemIntr->getBasePtr(),
43447                                  MemIntr->getPointerInfo(),
43448                                  MemIntr->getOriginalAlign(),
43449                                  MemIntr->getMemOperand()->getFlags());
43450       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
43451       return Load;
43452     }
43453   }
43454 
43455   // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
43456   // TODO: Move to DAGCombine?
43457   if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
43458       SrcBC.getValueType().isInteger() &&
43459       (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
43460       SrcBC.getScalarValueSizeInBits() ==
43461           SrcBC.getOperand(0).getValueSizeInBits()) {
43462     unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
43463     if (IdxC.ult(Scale)) {
43464       unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
43465       SDValue Scl = SrcBC.getOperand(0);
43466       EVT SclVT = Scl.getValueType();
43467       if (Offset) {
43468         Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
43469                           DAG.getShiftAmountConstant(Offset, SclVT, dl));
43470       }
43471       Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
43472       Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
43473       return Scl;
43474     }
43475   }
43476 
43477   // Handle extract(truncate(x)) for 0'th index.
43478   // TODO: Treat this as a faux shuffle?
43479   // TODO: When can we use this for general indices?
43480   if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
43481       (SrcVT.getSizeInBits() % 128) == 0) {
43482     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
43483     MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
43484     return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
43485                        Idx);
43486   }
43487 
43488   // We can only legally extract other elements from 128-bit vectors and in
43489   // certain circumstances, depending on SSE-level.
43490   // TODO: Investigate float/double extraction if it will be just stored.
43491   auto GetLegalExtract = [&Subtarget, &DAG, &dl](SDValue Vec, EVT VecVT,
43492                                                  unsigned Idx) {
43493     EVT VecSVT = VecVT.getScalarType();
43494     if ((VecVT.is256BitVector() || VecVT.is512BitVector()) &&
43495         (VecSVT == MVT::i8 || VecSVT == MVT::i16 || VecSVT == MVT::i32 ||
43496          VecSVT == MVT::i64)) {
43497       unsigned EltSizeInBits = VecSVT.getSizeInBits();
43498       unsigned NumEltsPerLane = 128 / EltSizeInBits;
43499       unsigned LaneOffset = (Idx & ~(NumEltsPerLane - 1)) * EltSizeInBits;
43500       unsigned LaneIdx = LaneOffset / Vec.getScalarValueSizeInBits();
43501       VecVT = EVT::getVectorVT(*DAG.getContext(), VecSVT, NumEltsPerLane);
43502       Vec = extract128BitVector(Vec, LaneIdx, DAG, dl);
43503       Idx &= (NumEltsPerLane - 1);
43504     }
43505     if ((VecVT == MVT::v4i32 || VecVT == MVT::v2i64) &&
43506         ((Idx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
43507       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VecVT.getScalarType(),
43508                          DAG.getBitcast(VecVT, Vec),
43509                          DAG.getIntPtrConstant(Idx, dl));
43510     }
43511     if ((VecVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
43512         (VecVT == MVT::v16i8 && Subtarget.hasSSE41())) {
43513       unsigned OpCode = (VecVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
43514       return DAG.getNode(OpCode, dl, MVT::i32, DAG.getBitcast(VecVT, Vec),
43515                          DAG.getTargetConstant(Idx, dl, MVT::i8));
43516     }
43517     return SDValue();
43518   };
43519 
43520   // Resolve the target shuffle inputs and mask.
43521   SmallVector<int, 16> Mask;
43522   SmallVector<SDValue, 2> Ops;
43523   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
43524     return SDValue();
43525 
43526   // Shuffle inputs must be the same size as the result.
43527   if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
43528         return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
43529       }))
43530     return SDValue();
43531 
43532   // Attempt to narrow/widen the shuffle mask to the correct size.
43533   if (Mask.size() != NumSrcElts) {
43534     if ((NumSrcElts % Mask.size()) == 0) {
43535       SmallVector<int, 16> ScaledMask;
43536       int Scale = NumSrcElts / Mask.size();
43537       narrowShuffleMaskElts(Scale, Mask, ScaledMask);
43538       Mask = std::move(ScaledMask);
43539     } else if ((Mask.size() % NumSrcElts) == 0) {
43540       // Simplify Mask based on demanded element.
43541       int ExtractIdx = (int)IdxC.getZExtValue();
43542       int Scale = Mask.size() / NumSrcElts;
43543       int Lo = Scale * ExtractIdx;
43544       int Hi = Scale * (ExtractIdx + 1);
43545       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
43546         if (i < Lo || Hi <= i)
43547           Mask[i] = SM_SentinelUndef;
43548 
43549       SmallVector<int, 16> WidenedMask;
43550       while (Mask.size() > NumSrcElts &&
43551              canWidenShuffleElements(Mask, WidenedMask))
43552         Mask = std::move(WidenedMask);
43553     }
43554   }
43555 
43556   // If narrowing/widening failed, see if we can extract+zero-extend.
43557   int ExtractIdx;
43558   EVT ExtractVT;
43559   if (Mask.size() == NumSrcElts) {
43560     ExtractIdx = Mask[IdxC.getZExtValue()];
43561     ExtractVT = SrcVT;
43562   } else {
43563     unsigned Scale = Mask.size() / NumSrcElts;
43564     if ((Mask.size() % NumSrcElts) != 0 || SrcVT.isFloatingPoint())
43565       return SDValue();
43566     unsigned ScaledIdx = Scale * IdxC.getZExtValue();
43567     if (!isUndefOrZeroInRange(Mask, ScaledIdx + 1, Scale - 1))
43568       return SDValue();
43569     ExtractIdx = Mask[ScaledIdx];
43570     EVT ExtractSVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltBits / Scale);
43571     ExtractVT = EVT::getVectorVT(*DAG.getContext(), ExtractSVT, Mask.size());
43572     assert(SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() &&
43573            "Failed to widen vector type");
43574   }
43575 
43576   // If the shuffle source element is undef/zero then we can just accept it.
43577   if (ExtractIdx == SM_SentinelUndef)
43578     return DAG.getUNDEF(VT);
43579 
43580   if (ExtractIdx == SM_SentinelZero)
43581     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
43582                                 : DAG.getConstant(0, dl, VT);
43583 
43584   SDValue SrcOp = Ops[ExtractIdx / Mask.size()];
43585   ExtractIdx = ExtractIdx % Mask.size();
43586   if (SDValue V = GetLegalExtract(SrcOp, ExtractVT, ExtractIdx))
43587     return DAG.getZExtOrTrunc(V, dl, VT);
43588 
43589   return SDValue();
43590 }
43591 
43592 /// Extracting a scalar FP value from vector element 0 is free, so extract each
43593 /// operand first, then perform the math as a scalar op.
43594 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG,
43595                                  const X86Subtarget &Subtarget) {
43596   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
43597   SDValue Vec = ExtElt->getOperand(0);
43598   SDValue Index = ExtElt->getOperand(1);
43599   EVT VT = ExtElt->getValueType(0);
43600   EVT VecVT = Vec.getValueType();
43601 
43602   // TODO: If this is a unary/expensive/expand op, allow extraction from a
43603   // non-zero element because the shuffle+scalar op will be cheaper?
43604   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
43605     return SDValue();
43606 
43607   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
43608   // extract, the condition code), so deal with those as a special-case.
43609   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
43610     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
43611     if (OpVT != MVT::f32 && OpVT != MVT::f64)
43612       return SDValue();
43613 
43614     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
43615     SDLoc DL(ExtElt);
43616     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
43617                                Vec.getOperand(0), Index);
43618     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
43619                                Vec.getOperand(1), Index);
43620     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
43621   }
43622 
43623   if (!(VT == MVT::f16 && Subtarget.hasFP16()) && VT != MVT::f32 &&
43624       VT != MVT::f64)
43625     return SDValue();
43626 
43627   // Vector FP selects don't fit the pattern of FP math ops (because the
43628   // condition has a different type and we have to change the opcode), so deal
43629   // with those here.
43630   // FIXME: This is restricted to pre type legalization by ensuring the setcc
43631   // has i1 elements. If we loosen this we need to convert vector bool to a
43632   // scalar bool.
43633   if (Vec.getOpcode() == ISD::VSELECT &&
43634       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
43635       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
43636       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
43637     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
43638     SDLoc DL(ExtElt);
43639     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
43640                                Vec.getOperand(0).getValueType().getScalarType(),
43641                                Vec.getOperand(0), Index);
43642     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
43643                                Vec.getOperand(1), Index);
43644     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
43645                                Vec.getOperand(2), Index);
43646     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
43647   }
43648 
43649   // TODO: This switch could include FNEG and the x86-specific FP logic ops
43650   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
43651   // missed load folding and fma+fneg combining.
43652   switch (Vec.getOpcode()) {
43653   case ISD::FMA: // Begin 3 operands
43654   case ISD::FMAD:
43655   case ISD::FADD: // Begin 2 operands
43656   case ISD::FSUB:
43657   case ISD::FMUL:
43658   case ISD::FDIV:
43659   case ISD::FREM:
43660   case ISD::FCOPYSIGN:
43661   case ISD::FMINNUM:
43662   case ISD::FMAXNUM:
43663   case ISD::FMINNUM_IEEE:
43664   case ISD::FMAXNUM_IEEE:
43665   case ISD::FMAXIMUM:
43666   case ISD::FMINIMUM:
43667   case X86ISD::FMAX:
43668   case X86ISD::FMIN:
43669   case ISD::FABS: // Begin 1 operand
43670   case ISD::FSQRT:
43671   case ISD::FRINT:
43672   case ISD::FCEIL:
43673   case ISD::FTRUNC:
43674   case ISD::FNEARBYINT:
43675   case ISD::FROUND:
43676   case ISD::FFLOOR:
43677   case X86ISD::FRCP:
43678   case X86ISD::FRSQRT: {
43679     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
43680     SDLoc DL(ExtElt);
43681     SmallVector<SDValue, 4> ExtOps;
43682     for (SDValue Op : Vec->ops())
43683       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
43684     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
43685   }
43686   default:
43687     return SDValue();
43688   }
43689   llvm_unreachable("All opcodes should return within switch");
43690 }
43691 
43692 /// Try to convert a vector reduction sequence composed of binops and shuffles
43693 /// into horizontal ops.
43694 static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
43695                                      const X86Subtarget &Subtarget) {
43696   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
43697 
43698   // We need at least SSE2 to anything here.
43699   if (!Subtarget.hasSSE2())
43700     return SDValue();
43701 
43702   ISD::NodeType Opc;
43703   SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
43704                                         {ISD::ADD, ISD::MUL, ISD::FADD}, true);
43705   if (!Rdx)
43706     return SDValue();
43707 
43708   SDValue Index = ExtElt->getOperand(1);
43709   assert(isNullConstant(Index) &&
43710          "Reduction doesn't end in an extract from index 0");
43711 
43712   EVT VT = ExtElt->getValueType(0);
43713   EVT VecVT = Rdx.getValueType();
43714   if (VecVT.getScalarType() != VT)
43715     return SDValue();
43716 
43717   SDLoc DL(ExtElt);
43718   unsigned NumElts = VecVT.getVectorNumElements();
43719   unsigned EltSizeInBits = VecVT.getScalarSizeInBits();
43720 
43721   // Extend v4i8/v8i8 vector to v16i8, with undef upper 64-bits.
43722   auto WidenToV16I8 = [&](SDValue V, bool ZeroExtend) {
43723     if (V.getValueType() == MVT::v4i8) {
43724       if (ZeroExtend && Subtarget.hasSSE41()) {
43725         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
43726                         DAG.getConstant(0, DL, MVT::v4i32),
43727                         DAG.getBitcast(MVT::i32, V),
43728                         DAG.getIntPtrConstant(0, DL));
43729         return DAG.getBitcast(MVT::v16i8, V);
43730       }
43731       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, V,
43732                       ZeroExtend ? DAG.getConstant(0, DL, MVT::v4i8)
43733                                  : DAG.getUNDEF(MVT::v4i8));
43734     }
43735     return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V,
43736                        DAG.getUNDEF(MVT::v8i8));
43737   };
43738 
43739   // vXi8 mul reduction - promote to vXi16 mul reduction.
43740   if (Opc == ISD::MUL) {
43741     if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
43742       return SDValue();
43743     if (VecVT.getSizeInBits() >= 128) {
43744       EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
43745       SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
43746       SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
43747       Lo = DAG.getBitcast(WideVT, Lo);
43748       Hi = DAG.getBitcast(WideVT, Hi);
43749       Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
43750       while (Rdx.getValueSizeInBits() > 128) {
43751         std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
43752         Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
43753       }
43754     } else {
43755       Rdx = WidenToV16I8(Rdx, false);
43756       Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
43757       Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
43758     }
43759     if (NumElts >= 8)
43760       Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
43761                         DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
43762                                              {4, 5, 6, 7, -1, -1, -1, -1}));
43763     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
43764                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
43765                                            {2, 3, -1, -1, -1, -1, -1, -1}));
43766     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
43767                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
43768                                            {1, -1, -1, -1, -1, -1, -1, -1}));
43769     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
43770     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
43771   }
43772 
43773   // vXi8 add reduction - sub 128-bit vector.
43774   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
43775     Rdx = WidenToV16I8(Rdx, true);
43776     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
43777                       DAG.getConstant(0, DL, MVT::v16i8));
43778     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
43779     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
43780   }
43781 
43782   // Must be a >=128-bit vector with pow2 elements.
43783   if ((VecVT.getSizeInBits() % 128) != 0 || !isPowerOf2_32(NumElts))
43784     return SDValue();
43785 
43786   // vXi8 add reduction - sum lo/hi halves then use PSADBW.
43787   if (VT == MVT::i8) {
43788     while (Rdx.getValueSizeInBits() > 128) {
43789       SDValue Lo, Hi;
43790       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
43791       VecVT = Lo.getValueType();
43792       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
43793     }
43794     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
43795 
43796     SDValue Hi = DAG.getVectorShuffle(
43797         MVT::v16i8, DL, Rdx, Rdx,
43798         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
43799     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
43800     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
43801                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
43802     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
43803     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
43804   }
43805 
43806   // See if we can use vXi8 PSADBW add reduction for larger zext types.
43807   // If the source vector values are 0-255, then we can use PSADBW to
43808   // sum+zext v8i8 subvectors to vXi64, then perform the reduction.
43809   // TODO: See if its worth avoiding vXi16/i32 truncations?
43810   if (Opc == ISD::ADD && NumElts >= 4 && EltSizeInBits >= 16 &&
43811       DAG.computeKnownBits(Rdx).getMaxValue().ule(255) &&
43812       (EltSizeInBits == 16 || Rdx.getOpcode() == ISD::ZERO_EXTEND ||
43813        Subtarget.hasAVX512())) {
43814     EVT ByteVT = VecVT.changeVectorElementType(MVT::i8);
43815     Rdx = DAG.getNode(ISD::TRUNCATE, DL, ByteVT, Rdx);
43816     if (ByteVT.getSizeInBits() < 128)
43817       Rdx = WidenToV16I8(Rdx, true);
43818 
43819     // Build the PSADBW, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
43820     auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43821                             ArrayRef<SDValue> Ops) {
43822       MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
43823       SDValue Zero = DAG.getConstant(0, DL, Ops[0].getValueType());
43824       return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops[0], Zero);
43825     };
43826     MVT SadVT = MVT::getVectorVT(MVT::i64, Rdx.getValueSizeInBits() / 64);
43827     Rdx = SplitOpsAndApply(DAG, Subtarget, DL, SadVT, {Rdx}, PSADBWBuilder);
43828 
43829     // TODO: We could truncate to vXi16/vXi32 before performing the reduction.
43830     while (Rdx.getValueSizeInBits() > 128) {
43831       SDValue Lo, Hi;
43832       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
43833       VecVT = Lo.getValueType();
43834       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
43835     }
43836     assert(Rdx.getValueType() == MVT::v2i64 && "v2i64 reduction expected");
43837 
43838     if (NumElts > 8) {
43839       SDValue RdxHi = DAG.getVectorShuffle(MVT::v2i64, DL, Rdx, Rdx, {1, -1});
43840       Rdx = DAG.getNode(ISD::ADD, DL, MVT::v2i64, Rdx, RdxHi);
43841     }
43842 
43843     VecVT = MVT::getVectorVT(VT.getSimpleVT(), 128 / VT.getSizeInBits());
43844     Rdx = DAG.getBitcast(VecVT, Rdx);
43845     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
43846   }
43847 
43848   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
43849   if (!shouldUseHorizontalOp(true, DAG, Subtarget))
43850     return SDValue();
43851 
43852   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
43853 
43854   // 256-bit horizontal instructions operate on 128-bit chunks rather than
43855   // across the whole vector, so we need an extract + hop preliminary stage.
43856   // This is the only step where the operands of the hop are not the same value.
43857   // TODO: We could extend this to handle 512-bit or even longer vectors.
43858   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
43859       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
43860     unsigned NumElts = VecVT.getVectorNumElements();
43861     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
43862     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
43863     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
43864     VecVT = Rdx.getValueType();
43865   }
43866   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
43867       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
43868     return SDValue();
43869 
43870   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
43871   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
43872   for (unsigned i = 0; i != ReductionSteps; ++i)
43873     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
43874 
43875   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
43876 }
43877 
43878 /// Detect vector gather/scatter index generation and convert it from being a
43879 /// bunch of shuffles and extracts into a somewhat faster sequence.
43880 /// For i686, the best sequence is apparently storing the value and loading
43881 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
43882 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
43883                                        TargetLowering::DAGCombinerInfo &DCI,
43884                                        const X86Subtarget &Subtarget) {
43885   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
43886     return NewOp;
43887 
43888   SDValue InputVector = N->getOperand(0);
43889   SDValue EltIdx = N->getOperand(1);
43890   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
43891 
43892   EVT SrcVT = InputVector.getValueType();
43893   EVT VT = N->getValueType(0);
43894   SDLoc dl(InputVector);
43895   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
43896   unsigned NumSrcElts = SrcVT.getVectorNumElements();
43897 
43898   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
43899     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
43900 
43901   // Integer Constant Folding.
43902   if (CIdx && VT.isInteger()) {
43903     APInt UndefVecElts;
43904     SmallVector<APInt, 16> EltBits;
43905     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
43906     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
43907                                       EltBits, true, false)) {
43908       uint64_t Idx = CIdx->getZExtValue();
43909       if (UndefVecElts[Idx])
43910         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
43911       return DAG.getConstant(EltBits[Idx].zext(VT.getScalarSizeInBits()), dl,
43912                              VT);
43913     }
43914   }
43915 
43916   if (IsPextr) {
43917     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43918     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
43919                                  APInt::getAllOnes(VT.getSizeInBits()), DCI))
43920       return SDValue(N, 0);
43921 
43922     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
43923     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
43924          InputVector.getOpcode() == X86ISD::PINSRW) &&
43925         InputVector.getOperand(2) == EltIdx) {
43926       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
43927              "Vector type mismatch");
43928       SDValue Scl = InputVector.getOperand(1);
43929       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
43930       return DAG.getZExtOrTrunc(Scl, dl, VT);
43931     }
43932 
43933     // TODO - Remove this once we can handle the implicit zero-extension of
43934     // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
43935     // combineBasicSADPattern.
43936     return SDValue();
43937   }
43938 
43939   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
43940   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
43941       VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
43942     SDValue MMXSrc = InputVector.getOperand(0);
43943 
43944     // The bitcast source is a direct mmx result.
43945     if (MMXSrc.getValueType() == MVT::x86mmx)
43946       return DAG.getBitcast(VT, InputVector);
43947   }
43948 
43949   // Detect mmx to i32 conversion through a v2i32 elt extract.
43950   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
43951       VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
43952     SDValue MMXSrc = InputVector.getOperand(0);
43953 
43954     // The bitcast source is a direct mmx result.
43955     if (MMXSrc.getValueType() == MVT::x86mmx)
43956       return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
43957   }
43958 
43959   // Check whether this extract is the root of a sum of absolute differences
43960   // pattern. This has to be done here because we really want it to happen
43961   // pre-legalization,
43962   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
43963     return SAD;
43964 
43965   if (SDValue VPDPBUSD = combineVPDPBUSDPattern(N, DAG, Subtarget))
43966     return VPDPBUSD;
43967 
43968   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
43969   if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
43970     return Cmp;
43971 
43972   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
43973   if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
43974     return MinMax;
43975 
43976   // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
43977   if (SDValue V = combineArithReduction(N, DAG, Subtarget))
43978     return V;
43979 
43980   if (SDValue V = scalarizeExtEltFP(N, DAG, Subtarget))
43981     return V;
43982 
43983   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
43984   // and then testing the relevant element.
43985   //
43986   // Note that we only combine extracts on the *same* result number, i.e.
43987   //   t0 = merge_values a0, a1, a2, a3
43988   //   i1 = extract_vector_elt t0, Constant:i64<2>
43989   //   i1 = extract_vector_elt t0, Constant:i64<3>
43990   // but not
43991   //   i1 = extract_vector_elt t0:1, Constant:i64<2>
43992   // since the latter would need its own MOVMSK.
43993   if (SrcVT.getScalarType() == MVT::i1) {
43994     bool IsVar = !CIdx;
43995     SmallVector<SDNode *, 16> BoolExtracts;
43996     unsigned ResNo = InputVector.getResNo();
43997     auto IsBoolExtract = [&BoolExtracts, &ResNo, &IsVar](SDNode *Use) {
43998       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
43999           Use->getOperand(0).getResNo() == ResNo &&
44000           Use->getValueType(0) == MVT::i1) {
44001         BoolExtracts.push_back(Use);
44002         IsVar |= !isa<ConstantSDNode>(Use->getOperand(1));
44003         return true;
44004       }
44005       return false;
44006     };
44007     // TODO: Can we drop the oneuse check for constant extracts?
44008     if (all_of(InputVector->uses(), IsBoolExtract) &&
44009         (IsVar || BoolExtracts.size() > 1)) {
44010       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
44011       if (SDValue BC =
44012               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
44013         for (SDNode *Use : BoolExtracts) {
44014           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
44015           // Mask = 1 << MaskIdx
44016           SDValue MaskIdx = DAG.getZExtOrTrunc(Use->getOperand(1), dl, MVT::i8);
44017           SDValue MaskBit = DAG.getConstant(1, dl, BCVT);
44018           SDValue Mask = DAG.getNode(ISD::SHL, dl, BCVT, MaskBit, MaskIdx);
44019           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
44020           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
44021           DCI.CombineTo(Use, Res);
44022         }
44023         return SDValue(N, 0);
44024       }
44025     }
44026   }
44027 
44028   // If this extract is from a loaded vector value and will be used as an
44029   // integer, that requires a potentially expensive XMM -> GPR transfer.
44030   // Additionally, if we can convert to a scalar integer load, that will likely
44031   // be folded into a subsequent integer op.
44032   // Note: Unlike the related fold for this in DAGCombiner, this is not limited
44033   //       to a single-use of the loaded vector. For the reasons above, we
44034   //       expect this to be profitable even if it creates an extra load.
44035   bool LikelyUsedAsVector = any_of(N->uses(), [](SDNode *Use) {
44036     return Use->getOpcode() == ISD::STORE ||
44037            Use->getOpcode() == ISD::INSERT_VECTOR_ELT ||
44038            Use->getOpcode() == ISD::SCALAR_TO_VECTOR;
44039   });
44040   auto *LoadVec = dyn_cast<LoadSDNode>(InputVector);
44041   if (LoadVec && CIdx && ISD::isNormalLoad(LoadVec) && VT.isInteger() &&
44042       SrcVT.getVectorElementType() == VT && DCI.isAfterLegalizeDAG() &&
44043       !LikelyUsedAsVector && LoadVec->isSimple()) {
44044     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44045     SDValue NewPtr =
44046         TLI.getVectorElementPointer(DAG, LoadVec->getBasePtr(), SrcVT, EltIdx);
44047     unsigned PtrOff = VT.getSizeInBits() * CIdx->getZExtValue() / 8;
44048     MachinePointerInfo MPI = LoadVec->getPointerInfo().getWithOffset(PtrOff);
44049     Align Alignment = commonAlignment(LoadVec->getAlign(), PtrOff);
44050     SDValue Load =
44051         DAG.getLoad(VT, dl, LoadVec->getChain(), NewPtr, MPI, Alignment,
44052                     LoadVec->getMemOperand()->getFlags(), LoadVec->getAAInfo());
44053     DAG.makeEquivalentMemoryOrdering(LoadVec, Load);
44054     return Load;
44055   }
44056 
44057   return SDValue();
44058 }
44059 
44060 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
44061 // This is more or less the reverse of combineBitcastvxi1.
44062 static SDValue combineToExtendBoolVectorInReg(
44063     unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N0, SelectionDAG &DAG,
44064     TargetLowering::DAGCombinerInfo &DCI, const X86Subtarget &Subtarget) {
44065   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
44066       Opcode != ISD::ANY_EXTEND)
44067     return SDValue();
44068   if (!DCI.isBeforeLegalizeOps())
44069     return SDValue();
44070   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
44071     return SDValue();
44072 
44073   EVT SVT = VT.getScalarType();
44074   EVT InSVT = N0.getValueType().getScalarType();
44075   unsigned EltSizeInBits = SVT.getSizeInBits();
44076 
44077   // Input type must be extending a bool vector (bit-casted from a scalar
44078   // integer) to legal integer types.
44079   if (!VT.isVector())
44080     return SDValue();
44081   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
44082     return SDValue();
44083   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
44084     return SDValue();
44085 
44086   SDValue N00 = N0.getOperand(0);
44087   EVT SclVT = N00.getValueType();
44088   if (!SclVT.isScalarInteger())
44089     return SDValue();
44090 
44091   SDValue Vec;
44092   SmallVector<int> ShuffleMask;
44093   unsigned NumElts = VT.getVectorNumElements();
44094   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
44095 
44096   // Broadcast the scalar integer to the vector elements.
44097   if (NumElts > EltSizeInBits) {
44098     // If the scalar integer is greater than the vector element size, then we
44099     // must split it down into sub-sections for broadcasting. For example:
44100     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
44101     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
44102     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
44103     unsigned Scale = NumElts / EltSizeInBits;
44104     EVT BroadcastVT = EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
44105     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
44106     Vec = DAG.getBitcast(VT, Vec);
44107 
44108     for (unsigned i = 0; i != Scale; ++i)
44109       ShuffleMask.append(EltSizeInBits, i);
44110     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
44111   } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
44112              (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
44113     // If we have register broadcast instructions, use the scalar size as the
44114     // element type for the shuffle. Then cast to the wider element type. The
44115     // widened bits won't be used, and this might allow the use of a broadcast
44116     // load.
44117     assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
44118     unsigned Scale = EltSizeInBits / NumElts;
44119     EVT BroadcastVT =
44120         EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
44121     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
44122     ShuffleMask.append(NumElts * Scale, 0);
44123     Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
44124     Vec = DAG.getBitcast(VT, Vec);
44125   } else {
44126     // For smaller scalar integers, we can simply any-extend it to the vector
44127     // element size (we don't care about the upper bits) and broadcast it to all
44128     // elements.
44129     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
44130     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
44131     ShuffleMask.append(NumElts, 0);
44132     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
44133   }
44134 
44135   // Now, mask the relevant bit in each element.
44136   SmallVector<SDValue, 32> Bits;
44137   for (unsigned i = 0; i != NumElts; ++i) {
44138     int BitIdx = (i % EltSizeInBits);
44139     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
44140     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
44141   }
44142   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
44143   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
44144 
44145   // Compare against the bitmask and extend the result.
44146   EVT CCVT = VT.changeVectorElementType(MVT::i1);
44147   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
44148   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
44149 
44150   // For SEXT, this is now done, otherwise shift the result down for
44151   // zero-extension.
44152   if (Opcode == ISD::SIGN_EXTEND)
44153     return Vec;
44154   return DAG.getNode(ISD::SRL, DL, VT, Vec,
44155                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
44156 }
44157 
44158 /// If a vector select has an operand that is -1 or 0, try to simplify the
44159 /// select to a bitwise logic operation.
44160 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
44161 static SDValue
44162 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
44163                                  TargetLowering::DAGCombinerInfo &DCI,
44164                                  const X86Subtarget &Subtarget) {
44165   SDValue Cond = N->getOperand(0);
44166   SDValue LHS = N->getOperand(1);
44167   SDValue RHS = N->getOperand(2);
44168   EVT VT = LHS.getValueType();
44169   EVT CondVT = Cond.getValueType();
44170   SDLoc DL(N);
44171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44172 
44173   if (N->getOpcode() != ISD::VSELECT)
44174     return SDValue();
44175 
44176   assert(CondVT.isVector() && "Vector select expects a vector selector!");
44177 
44178   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
44179   // TODO: Can we assert that both operands are not zeros (because that should
44180   //       get simplified at node creation time)?
44181   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
44182   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
44183 
44184   // If both inputs are 0/undef, create a complete zero vector.
44185   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
44186   if (TValIsAllZeros && FValIsAllZeros) {
44187     if (VT.isFloatingPoint())
44188       return DAG.getConstantFP(0.0, DL, VT);
44189     return DAG.getConstant(0, DL, VT);
44190   }
44191 
44192   // To use the condition operand as a bitwise mask, it must have elements that
44193   // are the same size as the select elements. Ie, the condition operand must
44194   // have already been promoted from the IR select condition type <N x i1>.
44195   // Don't check if the types themselves are equal because that excludes
44196   // vector floating-point selects.
44197   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
44198     return SDValue();
44199 
44200   // Try to invert the condition if true value is not all 1s and false value is
44201   // not all 0s. Only do this if the condition has one use.
44202   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
44203   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
44204       // Check if the selector will be produced by CMPP*/PCMP*.
44205       Cond.getOpcode() == ISD::SETCC &&
44206       // Check if SETCC has already been promoted.
44207       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
44208           CondVT) {
44209     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
44210 
44211     if (TValIsAllZeros || FValIsAllOnes) {
44212       SDValue CC = Cond.getOperand(2);
44213       ISD::CondCode NewCC = ISD::getSetCCInverse(
44214           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
44215       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
44216                           NewCC);
44217       std::swap(LHS, RHS);
44218       TValIsAllOnes = FValIsAllOnes;
44219       FValIsAllZeros = TValIsAllZeros;
44220     }
44221   }
44222 
44223   // Cond value must be 'sign splat' to be converted to a logical op.
44224   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
44225     return SDValue();
44226 
44227   // vselect Cond, 111..., 000... -> Cond
44228   if (TValIsAllOnes && FValIsAllZeros)
44229     return DAG.getBitcast(VT, Cond);
44230 
44231   if (!TLI.isTypeLegal(CondVT))
44232     return SDValue();
44233 
44234   // vselect Cond, 111..., X -> or Cond, X
44235   if (TValIsAllOnes) {
44236     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
44237     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
44238     return DAG.getBitcast(VT, Or);
44239   }
44240 
44241   // vselect Cond, X, 000... -> and Cond, X
44242   if (FValIsAllZeros) {
44243     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
44244     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
44245     return DAG.getBitcast(VT, And);
44246   }
44247 
44248   // vselect Cond, 000..., X -> andn Cond, X
44249   if (TValIsAllZeros) {
44250     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
44251     SDValue AndN;
44252     // The canonical form differs for i1 vectors - x86andnp is not used
44253     if (CondVT.getScalarType() == MVT::i1)
44254       AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
44255                          CastRHS);
44256     else
44257       AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
44258     return DAG.getBitcast(VT, AndN);
44259   }
44260 
44261   return SDValue();
44262 }
44263 
44264 /// If both arms of a vector select are concatenated vectors, split the select,
44265 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
44266 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
44267 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
44268 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
44269                                   const X86Subtarget &Subtarget) {
44270   unsigned Opcode = N->getOpcode();
44271   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
44272     return SDValue();
44273 
44274   // TODO: Split 512-bit vectors too?
44275   EVT VT = N->getValueType(0);
44276   if (!VT.is256BitVector())
44277     return SDValue();
44278 
44279   // TODO: Split as long as any 2 of the 3 operands are concatenated?
44280   SDValue Cond = N->getOperand(0);
44281   SDValue TVal = N->getOperand(1);
44282   SDValue FVal = N->getOperand(2);
44283   SmallVector<SDValue, 4> CatOpsT, CatOpsF;
44284   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
44285       !collectConcatOps(TVal.getNode(), CatOpsT, DAG) ||
44286       !collectConcatOps(FVal.getNode(), CatOpsF, DAG))
44287     return SDValue();
44288 
44289   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
44290                             ArrayRef<SDValue> Ops) {
44291     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
44292   };
44293   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
44294                           makeBlend, /*CheckBWI*/ false);
44295 }
44296 
44297 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
44298   SDValue Cond = N->getOperand(0);
44299   SDValue LHS = N->getOperand(1);
44300   SDValue RHS = N->getOperand(2);
44301   SDLoc DL(N);
44302 
44303   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
44304   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
44305   if (!TrueC || !FalseC)
44306     return SDValue();
44307 
44308   // Don't do this for crazy integer types.
44309   EVT VT = N->getValueType(0);
44310   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
44311     return SDValue();
44312 
44313   // We're going to use the condition bit in math or logic ops. We could allow
44314   // this with a wider condition value (post-legalization it becomes an i8),
44315   // but if nothing is creating selects that late, it doesn't matter.
44316   if (Cond.getValueType() != MVT::i1)
44317     return SDValue();
44318 
44319   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
44320   // 3, 5, or 9 with i32/i64, so those get transformed too.
44321   // TODO: For constants that overflow or do not differ by power-of-2 or small
44322   // multiplier, convert to 'and' + 'add'.
44323   const APInt &TrueVal = TrueC->getAPIntValue();
44324   const APInt &FalseVal = FalseC->getAPIntValue();
44325 
44326   // We have a more efficient lowering for "(X == 0) ? Y : -1" using SBB.
44327   if ((TrueVal.isAllOnes() || FalseVal.isAllOnes()) &&
44328       Cond.getOpcode() == ISD::SETCC && isNullConstant(Cond.getOperand(1))) {
44329     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
44330     if (CC == ISD::SETEQ || CC == ISD::SETNE)
44331       return SDValue();
44332   }
44333 
44334   bool OV;
44335   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
44336   if (OV)
44337     return SDValue();
44338 
44339   APInt AbsDiff = Diff.abs();
44340   if (AbsDiff.isPowerOf2() ||
44341       ((VT == MVT::i32 || VT == MVT::i64) &&
44342        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
44343 
44344     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
44345     // of the condition can usually be folded into a compare predicate, but even
44346     // without that, the sequence should be cheaper than a CMOV alternative.
44347     if (TrueVal.slt(FalseVal)) {
44348       Cond = DAG.getNOT(DL, Cond, MVT::i1);
44349       std::swap(TrueC, FalseC);
44350     }
44351 
44352     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
44353     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
44354 
44355     // Multiply condition by the difference if non-one.
44356     if (!AbsDiff.isOne())
44357       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
44358 
44359     // Add the base if non-zero.
44360     if (!FalseC->isZero())
44361       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
44362 
44363     return R;
44364   }
44365 
44366   return SDValue();
44367 }
44368 
44369 /// If this is a *dynamic* select (non-constant condition) and we can match
44370 /// this node with one of the variable blend instructions, restructure the
44371 /// condition so that blends can use the high (sign) bit of each element.
44372 /// This function will also call SimplifyDemandedBits on already created
44373 /// BLENDV to perform additional simplifications.
44374 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
44375                                       TargetLowering::DAGCombinerInfo &DCI,
44376                                       const X86Subtarget &Subtarget) {
44377   SDValue Cond = N->getOperand(0);
44378   if ((N->getOpcode() != ISD::VSELECT &&
44379        N->getOpcode() != X86ISD::BLENDV) ||
44380       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
44381     return SDValue();
44382 
44383   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44384   unsigned BitWidth = Cond.getScalarValueSizeInBits();
44385   EVT VT = N->getValueType(0);
44386 
44387   // We can only handle the cases where VSELECT is directly legal on the
44388   // subtarget. We custom lower VSELECT nodes with constant conditions and
44389   // this makes it hard to see whether a dynamic VSELECT will correctly
44390   // lower, so we both check the operation's status and explicitly handle the
44391   // cases where a *dynamic* blend will fail even though a constant-condition
44392   // blend could be custom lowered.
44393   // FIXME: We should find a better way to handle this class of problems.
44394   // Potentially, we should combine constant-condition vselect nodes
44395   // pre-legalization into shuffles and not mark as many types as custom
44396   // lowered.
44397   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
44398     return SDValue();
44399   // FIXME: We don't support i16-element blends currently. We could and
44400   // should support them by making *all* the bits in the condition be set
44401   // rather than just the high bit and using an i8-element blend.
44402   if (VT.getVectorElementType() == MVT::i16)
44403     return SDValue();
44404   // Dynamic blending was only available from SSE4.1 onward.
44405   if (VT.is128BitVector() && !Subtarget.hasSSE41())
44406     return SDValue();
44407   // Byte blends are only available in AVX2
44408   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
44409     return SDValue();
44410   // There are no 512-bit blend instructions that use sign bits.
44411   if (VT.is512BitVector())
44412     return SDValue();
44413 
44414   // Don't optimize before the condition has been transformed to a legal type
44415   // and don't ever optimize vector selects that map to AVX512 mask-registers.
44416   if (BitWidth < 8 || BitWidth > 64)
44417     return SDValue();
44418 
44419   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
44420     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
44421          UI != UE; ++UI)
44422       if ((UI->getOpcode() != ISD::VSELECT &&
44423            UI->getOpcode() != X86ISD::BLENDV) ||
44424           UI.getOperandNo() != 0)
44425         return false;
44426 
44427     return true;
44428   };
44429 
44430   APInt DemandedBits(APInt::getSignMask(BitWidth));
44431 
44432   if (OnlyUsedAsSelectCond(Cond)) {
44433     KnownBits Known;
44434     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
44435                                           !DCI.isBeforeLegalizeOps());
44436     if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
44437       return SDValue();
44438 
44439     // If we changed the computation somewhere in the DAG, this change will
44440     // affect all users of Cond. Update all the nodes so that we do not use
44441     // the generic VSELECT anymore. Otherwise, we may perform wrong
44442     // optimizations as we messed with the actual expectation for the vector
44443     // boolean values.
44444     for (SDNode *U : Cond->uses()) {
44445       if (U->getOpcode() == X86ISD::BLENDV)
44446         continue;
44447 
44448       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
44449                                Cond, U->getOperand(1), U->getOperand(2));
44450       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
44451       DCI.AddToWorklist(U);
44452     }
44453     DCI.CommitTargetLoweringOpt(TLO);
44454     return SDValue(N, 0);
44455   }
44456 
44457   // Otherwise we can still at least try to simplify multiple use bits.
44458   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
44459       return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
44460                          N->getOperand(1), N->getOperand(2));
44461 
44462   return SDValue();
44463 }
44464 
44465 // Try to match:
44466 //   (or (and (M, (sub 0, X)), (pandn M, X)))
44467 // which is a special case of:
44468 //   (select M, (sub 0, X), X)
44469 // Per:
44470 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
44471 // We know that, if fNegate is 0 or 1:
44472 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
44473 //
44474 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
44475 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
44476 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
44477 // This lets us transform our vselect to:
44478 //   (add (xor X, M), (and M, 1))
44479 // And further to:
44480 //   (sub (xor X, M), M)
44481 static SDValue combineLogicBlendIntoConditionalNegate(
44482     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
44483     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
44484   EVT MaskVT = Mask.getValueType();
44485   assert(MaskVT.isInteger() &&
44486          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
44487          "Mask must be zero/all-bits");
44488 
44489   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
44490     return SDValue();
44491   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
44492     return SDValue();
44493 
44494   auto IsNegV = [](SDNode *N, SDValue V) {
44495     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
44496            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
44497   };
44498 
44499   SDValue V;
44500   if (IsNegV(Y.getNode(), X))
44501     V = X;
44502   else if (IsNegV(X.getNode(), Y))
44503     V = Y;
44504   else
44505     return SDValue();
44506 
44507   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
44508   SDValue SubOp2 = Mask;
44509 
44510   // If the negate was on the false side of the select, then
44511   // the operands of the SUB need to be swapped. PR 27251.
44512   // This is because the pattern being matched above is
44513   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
44514   // but if the pattern matched was
44515   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
44516   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
44517   // pattern also needs to be a negation of the replacement pattern above.
44518   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
44519   // sub accomplishes the negation of the replacement pattern.
44520   if (V == Y)
44521     std::swap(SubOp1, SubOp2);
44522 
44523   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
44524   return DAG.getBitcast(VT, Res);
44525 }
44526 
44527 /// Do target-specific dag combines on SELECT and VSELECT nodes.
44528 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
44529                              TargetLowering::DAGCombinerInfo &DCI,
44530                              const X86Subtarget &Subtarget) {
44531   SDLoc DL(N);
44532   SDValue Cond = N->getOperand(0);
44533   SDValue LHS = N->getOperand(1);
44534   SDValue RHS = N->getOperand(2);
44535 
44536   // Try simplification again because we use this function to optimize
44537   // BLENDV nodes that are not handled by the generic combiner.
44538   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
44539     return V;
44540 
44541   EVT VT = LHS.getValueType();
44542   EVT CondVT = Cond.getValueType();
44543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44544   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
44545 
44546   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
44547   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
44548   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
44549   if (CondVT.isVector() && CondVT.isInteger() &&
44550       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
44551       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
44552       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
44553     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
44554                                                            DL, DAG, Subtarget))
44555       return V;
44556 
44557   // Convert vselects with constant condition into shuffles.
44558   if (CondConstantVector && DCI.isBeforeLegalizeOps() &&
44559       (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::BLENDV)) {
44560     SmallVector<int, 64> Mask;
44561     if (createShuffleMaskFromVSELECT(Mask, Cond,
44562                                      N->getOpcode() == X86ISD::BLENDV))
44563       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
44564   }
44565 
44566   // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
44567   // by forcing the unselected elements to zero.
44568   // TODO: Can we handle more shuffles with this?
44569   if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
44570       LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
44571       LHS.hasOneUse() && RHS.hasOneUse()) {
44572     MVT SimpleVT = VT.getSimpleVT();
44573     SmallVector<SDValue, 1> LHSOps, RHSOps;
44574     SmallVector<int, 64> LHSMask, RHSMask, CondMask;
44575     if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
44576         getTargetShuffleMask(LHS.getNode(), SimpleVT, true, LHSOps, LHSMask) &&
44577         getTargetShuffleMask(RHS.getNode(), SimpleVT, true, RHSOps, RHSMask)) {
44578       int NumElts = VT.getVectorNumElements();
44579       for (int i = 0; i != NumElts; ++i) {
44580         // getConstVector sets negative shuffle mask values as undef, so ensure
44581         // we hardcode SM_SentinelZero values to zero (0x80).
44582         if (CondMask[i] < NumElts) {
44583           LHSMask[i] = isUndefOrZero(LHSMask[i]) ? 0x80 : LHSMask[i];
44584           RHSMask[i] = 0x80;
44585         } else {
44586           LHSMask[i] = 0x80;
44587           RHSMask[i] = isUndefOrZero(RHSMask[i]) ? 0x80 : RHSMask[i];
44588         }
44589       }
44590       LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
44591                         getConstVector(LHSMask, SimpleVT, DAG, DL, true));
44592       RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
44593                         getConstVector(RHSMask, SimpleVT, DAG, DL, true));
44594       return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
44595     }
44596   }
44597 
44598   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
44599   // instructions match the semantics of the common C idiom x<y?x:y but not
44600   // x<=y?x:y, because of how they handle negative zero (which can be
44601   // ignored in unsafe-math mode).
44602   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
44603   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
44604       VT != MVT::f80 && VT != MVT::f128 && !isSoftFP16(VT, Subtarget) &&
44605       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
44606       (Subtarget.hasSSE2() ||
44607        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
44608     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
44609 
44610     unsigned Opcode = 0;
44611     // Check for x CC y ? x : y.
44612     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
44613         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
44614       switch (CC) {
44615       default: break;
44616       case ISD::SETULT:
44617         // Converting this to a min would handle NaNs incorrectly, and swapping
44618         // the operands would cause it to handle comparisons between positive
44619         // and negative zero incorrectly.
44620         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
44621           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44622               !(DAG.isKnownNeverZeroFloat(LHS) ||
44623                 DAG.isKnownNeverZeroFloat(RHS)))
44624             break;
44625           std::swap(LHS, RHS);
44626         }
44627         Opcode = X86ISD::FMIN;
44628         break;
44629       case ISD::SETOLE:
44630         // Converting this to a min would handle comparisons between positive
44631         // and negative zero incorrectly.
44632         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44633             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
44634           break;
44635         Opcode = X86ISD::FMIN;
44636         break;
44637       case ISD::SETULE:
44638         // Converting this to a min would handle both negative zeros and NaNs
44639         // incorrectly, but we can swap the operands to fix both.
44640         std::swap(LHS, RHS);
44641         LLVM_FALLTHROUGH;
44642       case ISD::SETOLT:
44643       case ISD::SETLT:
44644       case ISD::SETLE:
44645         Opcode = X86ISD::FMIN;
44646         break;
44647 
44648       case ISD::SETOGE:
44649         // Converting this to a max would handle comparisons between positive
44650         // and negative zero incorrectly.
44651         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44652             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
44653           break;
44654         Opcode = X86ISD::FMAX;
44655         break;
44656       case ISD::SETUGT:
44657         // Converting this to a max would handle NaNs incorrectly, and swapping
44658         // the operands would cause it to handle comparisons between positive
44659         // and negative zero incorrectly.
44660         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
44661           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44662               !(DAG.isKnownNeverZeroFloat(LHS) ||
44663                 DAG.isKnownNeverZeroFloat(RHS)))
44664             break;
44665           std::swap(LHS, RHS);
44666         }
44667         Opcode = X86ISD::FMAX;
44668         break;
44669       case ISD::SETUGE:
44670         // Converting this to a max would handle both negative zeros and NaNs
44671         // incorrectly, but we can swap the operands to fix both.
44672         std::swap(LHS, RHS);
44673         LLVM_FALLTHROUGH;
44674       case ISD::SETOGT:
44675       case ISD::SETGT:
44676       case ISD::SETGE:
44677         Opcode = X86ISD::FMAX;
44678         break;
44679       }
44680     // Check for x CC y ? y : x -- a min/max with reversed arms.
44681     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
44682                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
44683       switch (CC) {
44684       default: break;
44685       case ISD::SETOGE:
44686         // Converting this to a min would handle comparisons between positive
44687         // and negative zero incorrectly, and swapping the operands would
44688         // cause it to handle NaNs incorrectly.
44689         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44690             !(DAG.isKnownNeverZeroFloat(LHS) ||
44691               DAG.isKnownNeverZeroFloat(RHS))) {
44692           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
44693             break;
44694           std::swap(LHS, RHS);
44695         }
44696         Opcode = X86ISD::FMIN;
44697         break;
44698       case ISD::SETUGT:
44699         // Converting this to a min would handle NaNs incorrectly.
44700         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
44701           break;
44702         Opcode = X86ISD::FMIN;
44703         break;
44704       case ISD::SETUGE:
44705         // Converting this to a min would handle both negative zeros and NaNs
44706         // incorrectly, but we can swap the operands to fix both.
44707         std::swap(LHS, RHS);
44708         LLVM_FALLTHROUGH;
44709       case ISD::SETOGT:
44710       case ISD::SETGT:
44711       case ISD::SETGE:
44712         Opcode = X86ISD::FMIN;
44713         break;
44714 
44715       case ISD::SETULT:
44716         // Converting this to a max would handle NaNs incorrectly.
44717         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
44718           break;
44719         Opcode = X86ISD::FMAX;
44720         break;
44721       case ISD::SETOLE:
44722         // Converting this to a max would handle comparisons between positive
44723         // and negative zero incorrectly, and swapping the operands would
44724         // cause it to handle NaNs incorrectly.
44725         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44726             !DAG.isKnownNeverZeroFloat(LHS) &&
44727             !DAG.isKnownNeverZeroFloat(RHS)) {
44728           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
44729             break;
44730           std::swap(LHS, RHS);
44731         }
44732         Opcode = X86ISD::FMAX;
44733         break;
44734       case ISD::SETULE:
44735         // Converting this to a max would handle both negative zeros and NaNs
44736         // incorrectly, but we can swap the operands to fix both.
44737         std::swap(LHS, RHS);
44738         LLVM_FALLTHROUGH;
44739       case ISD::SETOLT:
44740       case ISD::SETLT:
44741       case ISD::SETLE:
44742         Opcode = X86ISD::FMAX;
44743         break;
44744       }
44745     }
44746 
44747     if (Opcode)
44748       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
44749   }
44750 
44751   // Some mask scalar intrinsics rely on checking if only one bit is set
44752   // and implement it in C code like this:
44753   // A[0] = (U & 1) ? A[0] : W[0];
44754   // This creates some redundant instructions that break pattern matching.
44755   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
44756   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
44757       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
44758     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
44759     SDValue AndNode = Cond.getOperand(0);
44760     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
44761         isNullConstant(Cond.getOperand(1)) &&
44762         isOneConstant(AndNode.getOperand(1))) {
44763       // LHS and RHS swapped due to
44764       // setcc outputting 1 when AND resulted in 0 and vice versa.
44765       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
44766       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
44767     }
44768   }
44769 
44770   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
44771   // lowering on KNL. In this case we convert it to
44772   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
44773   // The same situation all vectors of i8 and i16 without BWI.
44774   // Make sure we extend these even before type legalization gets a chance to
44775   // split wide vectors.
44776   // Since SKX these selects have a proper lowering.
44777   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
44778       CondVT.getVectorElementType() == MVT::i1 &&
44779       (VT.getVectorElementType() == MVT::i8 ||
44780        VT.getVectorElementType() == MVT::i16)) {
44781     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
44782     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
44783   }
44784 
44785   // AVX512 - Extend select with zero to merge with target shuffle.
44786   // select(mask, extract_subvector(shuffle(x)), zero) -->
44787   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
44788   // TODO - support non target shuffles as well.
44789   if (Subtarget.hasAVX512() && CondVT.isVector() &&
44790       CondVT.getVectorElementType() == MVT::i1) {
44791     auto SelectableOp = [&TLI](SDValue Op) {
44792       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
44793              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
44794              isNullConstant(Op.getOperand(1)) &&
44795              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
44796              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
44797     };
44798 
44799     bool SelectableLHS = SelectableOp(LHS);
44800     bool SelectableRHS = SelectableOp(RHS);
44801     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
44802     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
44803 
44804     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
44805       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
44806                                 : RHS.getOperand(0).getValueType();
44807       EVT SrcCondVT = SrcVT.changeVectorElementType(MVT::i1);
44808       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
44809                             VT.getSizeInBits());
44810       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
44811                             VT.getSizeInBits());
44812       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
44813                          DAG.getUNDEF(SrcCondVT), Cond,
44814                          DAG.getIntPtrConstant(0, DL));
44815       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
44816       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
44817     }
44818   }
44819 
44820   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
44821     return V;
44822 
44823   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
44824       Cond.hasOneUse()) {
44825     EVT CondVT = Cond.getValueType();
44826     SDValue Cond0 = Cond.getOperand(0);
44827     SDValue Cond1 = Cond.getOperand(1);
44828     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
44829 
44830     // Canonicalize min/max:
44831     // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
44832     // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
44833     // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
44834     // the need for an extra compare against zero. e.g.
44835     // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
44836     // subl   %esi, %edi
44837     // testl  %edi, %edi
44838     // movl   $0, %eax
44839     // cmovgl %edi, %eax
44840     // =>
44841     // xorl   %eax, %eax
44842     // subl   %esi, $edi
44843     // cmovsl %eax, %edi
44844     //
44845     // We can also canonicalize
44846     //  (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
44847     //  (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
44848     // This allows the use of a test instruction for the compare.
44849     if (LHS == Cond0 && RHS == Cond1) {
44850       if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
44851           (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
44852         ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
44853         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
44854         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
44855       }
44856       if (CC == ISD::SETUGT && isOneConstant(RHS)) {
44857         ISD::CondCode NewCC = ISD::SETUGE;
44858         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
44859         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
44860       }
44861     }
44862 
44863     // Similar to DAGCombine's select(or(CC0,CC1),X,Y) fold but for legal types.
44864     // fold eq + gt/lt nested selects into ge/le selects
44865     // select (cmpeq Cond0, Cond1), LHS, (select (cmpugt Cond0, Cond1), LHS, Y)
44866     // --> (select (cmpuge Cond0, Cond1), LHS, Y)
44867     // select (cmpslt Cond0, Cond1), LHS, (select (cmpeq Cond0, Cond1), LHS, Y)
44868     // --> (select (cmpsle Cond0, Cond1), LHS, Y)
44869     // .. etc ..
44870     if (RHS.getOpcode() == ISD::SELECT && RHS.getOperand(1) == LHS &&
44871         RHS.getOperand(0).getOpcode() == ISD::SETCC) {
44872       SDValue InnerSetCC = RHS.getOperand(0);
44873       ISD::CondCode InnerCC =
44874           cast<CondCodeSDNode>(InnerSetCC.getOperand(2))->get();
44875       if ((CC == ISD::SETEQ || InnerCC == ISD::SETEQ) &&
44876           Cond0 == InnerSetCC.getOperand(0) &&
44877           Cond1 == InnerSetCC.getOperand(1)) {
44878         ISD::CondCode NewCC;
44879         switch (CC == ISD::SETEQ ? InnerCC : CC) {
44880         case ISD::SETGT:  NewCC = ISD::SETGE; break;
44881         case ISD::SETLT:  NewCC = ISD::SETLE; break;
44882         case ISD::SETUGT: NewCC = ISD::SETUGE; break;
44883         case ISD::SETULT: NewCC = ISD::SETULE; break;
44884         default: NewCC = ISD::SETCC_INVALID; break;
44885         }
44886         if (NewCC != ISD::SETCC_INVALID) {
44887           Cond = DAG.getSetCC(DL, CondVT, Cond0, Cond1, NewCC);
44888           return DAG.getSelect(DL, VT, Cond, LHS, RHS.getOperand(2));
44889         }
44890       }
44891     }
44892   }
44893 
44894   // Check if the first operand is all zeros and Cond type is vXi1.
44895   // If this an avx512 target we can improve the use of zero masking by
44896   // swapping the operands and inverting the condition.
44897   if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
44898       Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
44899       ISD::isBuildVectorAllZeros(LHS.getNode()) &&
44900       !ISD::isBuildVectorAllZeros(RHS.getNode())) {
44901     // Invert the cond to not(cond) : xor(op,allones)=not(op)
44902     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
44903     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
44904     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
44905   }
44906 
44907   // Attempt to convert a (vXi1 bitcast(iX Cond)) selection mask before it might
44908   // get split by legalization.
44909   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::BITCAST &&
44910       CondVT.getVectorElementType() == MVT::i1 && Cond.hasOneUse() &&
44911       TLI.isTypeLegal(VT.getScalarType())) {
44912     EVT ExtCondVT = VT.changeVectorElementTypeToInteger();
44913     if (SDValue ExtCond = combineToExtendBoolVectorInReg(
44914             ISD::SIGN_EXTEND, DL, ExtCondVT, Cond, DAG, DCI, Subtarget)) {
44915       ExtCond = DAG.getNode(ISD::TRUNCATE, DL, CondVT, ExtCond);
44916       return DAG.getSelect(DL, VT, ExtCond, LHS, RHS);
44917     }
44918   }
44919 
44920   // Early exit check
44921   if (!TLI.isTypeLegal(VT) || isSoftFP16(VT, Subtarget))
44922     return SDValue();
44923 
44924   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
44925     return V;
44926 
44927   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
44928     return V;
44929 
44930   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
44931     return V;
44932 
44933   // select(~Cond, X, Y) -> select(Cond, Y, X)
44934   if (CondVT.getScalarType() != MVT::i1) {
44935     if (SDValue CondNot = IsNOT(Cond, DAG))
44936       return DAG.getNode(N->getOpcode(), DL, VT,
44937                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
44938     // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the signbit.
44939     if (Cond.getOpcode() == X86ISD::PCMPGT && Cond.hasOneUse() &&
44940         ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode())) {
44941       Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
44942                          DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
44943       return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
44944     }
44945   }
44946 
44947   // Try to optimize vXi1 selects if both operands are either all constants or
44948   // bitcasts from scalar integer type. In that case we can convert the operands
44949   // to integer and use an integer select which will be converted to a CMOV.
44950   // We need to take a little bit of care to avoid creating an i64 type after
44951   // type legalization.
44952   if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
44953       VT.getVectorElementType() == MVT::i1 &&
44954       (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
44955     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
44956     bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
44957     bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
44958 
44959     if ((LHSIsConst ||
44960          (LHS.getOpcode() == ISD::BITCAST &&
44961           LHS.getOperand(0).getValueType() == IntVT)) &&
44962         (RHSIsConst ||
44963          (RHS.getOpcode() == ISD::BITCAST &&
44964           RHS.getOperand(0).getValueType() == IntVT))) {
44965       if (LHSIsConst)
44966         LHS = combinevXi1ConstantToInteger(LHS, DAG);
44967       else
44968         LHS = LHS.getOperand(0);
44969 
44970       if (RHSIsConst)
44971         RHS = combinevXi1ConstantToInteger(RHS, DAG);
44972       else
44973         RHS = RHS.getOperand(0);
44974 
44975       SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
44976       return DAG.getBitcast(VT, Select);
44977     }
44978   }
44979 
44980   // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
44981   // single bits, then invert the predicate and swap the select operands.
44982   // This can lower using a vector shift bit-hack rather than mask and compare.
44983   if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
44984       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
44985       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
44986       Cond.getOperand(0).getOpcode() == ISD::AND &&
44987       isNullOrNullSplat(Cond.getOperand(1)) &&
44988       cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
44989       Cond.getOperand(0).getValueType() == VT) {
44990     // The 'and' mask must be composed of power-of-2 constants.
44991     SDValue And = Cond.getOperand(0);
44992     auto *C = isConstOrConstSplat(And.getOperand(1));
44993     if (C && C->getAPIntValue().isPowerOf2()) {
44994       // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
44995       SDValue NotCond =
44996           DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
44997       return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
44998     }
44999 
45000     // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
45001     // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
45002     // 16-bit lacks a proper blendv.
45003     unsigned EltBitWidth = VT.getScalarSizeInBits();
45004     bool CanShiftBlend =
45005         TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
45006                                 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
45007                                 (Subtarget.hasXOP()));
45008     if (CanShiftBlend &&
45009         ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
45010           return C->getAPIntValue().isPowerOf2();
45011         })) {
45012       // Create a left-shift constant to get the mask bits over to the sign-bit.
45013       SDValue Mask = And.getOperand(1);
45014       SmallVector<int, 32> ShlVals;
45015       for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
45016         auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
45017         ShlVals.push_back(EltBitWidth - 1 -
45018                           MaskVal->getAPIntValue().exactLogBase2());
45019       }
45020       // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
45021       SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
45022       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
45023       SDValue NewCond =
45024           DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
45025       return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
45026     }
45027   }
45028 
45029   return SDValue();
45030 }
45031 
45032 /// Combine:
45033 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
45034 /// to:
45035 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
45036 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
45037 /// Note that this is only legal for some op/cc combinations.
45038 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
45039                                        SelectionDAG &DAG,
45040                                        const X86Subtarget &Subtarget) {
45041   // This combine only operates on CMP-like nodes.
45042   if (!(Cmp.getOpcode() == X86ISD::CMP ||
45043         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
45044     return SDValue();
45045 
45046   // Can't replace the cmp if it has more uses than the one we're looking at.
45047   // FIXME: We would like to be able to handle this, but would need to make sure
45048   // all uses were updated.
45049   if (!Cmp.hasOneUse())
45050     return SDValue();
45051 
45052   // This only applies to variations of the common case:
45053   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
45054   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
45055   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
45056   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
45057   // Using the proper condcodes (see below), overflow is checked for.
45058 
45059   // FIXME: We can generalize both constraints:
45060   // - XOR/OR/AND (if they were made to survive AtomicExpand)
45061   // - LHS != 1
45062   // if the result is compared.
45063 
45064   SDValue CmpLHS = Cmp.getOperand(0);
45065   SDValue CmpRHS = Cmp.getOperand(1);
45066   EVT CmpVT = CmpLHS.getValueType();
45067 
45068   if (!CmpLHS.hasOneUse())
45069     return SDValue();
45070 
45071   unsigned Opc = CmpLHS.getOpcode();
45072   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
45073     return SDValue();
45074 
45075   SDValue OpRHS = CmpLHS.getOperand(2);
45076   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
45077   if (!OpRHSC)
45078     return SDValue();
45079 
45080   APInt Addend = OpRHSC->getAPIntValue();
45081   if (Opc == ISD::ATOMIC_LOAD_SUB)
45082     Addend = -Addend;
45083 
45084   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
45085   if (!CmpRHSC)
45086     return SDValue();
45087 
45088   APInt Comparison = CmpRHSC->getAPIntValue();
45089   APInt NegAddend = -Addend;
45090 
45091   // See if we can adjust the CC to make the comparison match the negated
45092   // addend.
45093   if (Comparison != NegAddend) {
45094     APInt IncComparison = Comparison + 1;
45095     if (IncComparison == NegAddend) {
45096       if (CC == X86::COND_A && !Comparison.isMaxValue()) {
45097         Comparison = IncComparison;
45098         CC = X86::COND_AE;
45099       } else if (CC == X86::COND_LE && !Comparison.isMaxSignedValue()) {
45100         Comparison = IncComparison;
45101         CC = X86::COND_L;
45102       }
45103     }
45104     APInt DecComparison = Comparison - 1;
45105     if (DecComparison == NegAddend) {
45106       if (CC == X86::COND_AE && !Comparison.isMinValue()) {
45107         Comparison = DecComparison;
45108         CC = X86::COND_A;
45109       } else if (CC == X86::COND_L && !Comparison.isMinSignedValue()) {
45110         Comparison = DecComparison;
45111         CC = X86::COND_LE;
45112       }
45113     }
45114   }
45115 
45116   // If the addend is the negation of the comparison value, then we can do
45117   // a full comparison by emitting the atomic arithmetic as a locked sub.
45118   if (Comparison == NegAddend) {
45119     // The CC is fine, but we need to rewrite the LHS of the comparison as an
45120     // atomic sub.
45121     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
45122     auto AtomicSub = DAG.getAtomic(
45123         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpVT,
45124         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
45125         /*RHS*/ DAG.getConstant(NegAddend, SDLoc(CmpRHS), CmpVT),
45126         AN->getMemOperand());
45127     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
45128     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
45129     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
45130     return LockOp;
45131   }
45132 
45133   // We can handle comparisons with zero in a number of cases by manipulating
45134   // the CC used.
45135   if (!Comparison.isZero())
45136     return SDValue();
45137 
45138   if (CC == X86::COND_S && Addend == 1)
45139     CC = X86::COND_LE;
45140   else if (CC == X86::COND_NS && Addend == 1)
45141     CC = X86::COND_G;
45142   else if (CC == X86::COND_G && Addend == -1)
45143     CC = X86::COND_GE;
45144   else if (CC == X86::COND_LE && Addend == -1)
45145     CC = X86::COND_L;
45146   else
45147     return SDValue();
45148 
45149   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
45150   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
45151   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
45152   return LockOp;
45153 }
45154 
45155 // Check whether a boolean test is testing a boolean value generated by
45156 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
45157 // code.
45158 //
45159 // Simplify the following patterns:
45160 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
45161 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
45162 // to (Op EFLAGS Cond)
45163 //
45164 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
45165 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
45166 // to (Op EFLAGS !Cond)
45167 //
45168 // where Op could be BRCOND or CMOV.
45169 //
45170 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
45171   // This combine only operates on CMP-like nodes.
45172   if (!(Cmp.getOpcode() == X86ISD::CMP ||
45173         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
45174     return SDValue();
45175 
45176   // Quit if not used as a boolean value.
45177   if (CC != X86::COND_E && CC != X86::COND_NE)
45178     return SDValue();
45179 
45180   // Check CMP operands. One of them should be 0 or 1 and the other should be
45181   // an SetCC or extended from it.
45182   SDValue Op1 = Cmp.getOperand(0);
45183   SDValue Op2 = Cmp.getOperand(1);
45184 
45185   SDValue SetCC;
45186   const ConstantSDNode* C = nullptr;
45187   bool needOppositeCond = (CC == X86::COND_E);
45188   bool checkAgainstTrue = false; // Is it a comparison against 1?
45189 
45190   if ((C = dyn_cast<ConstantSDNode>(Op1)))
45191     SetCC = Op2;
45192   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
45193     SetCC = Op1;
45194   else // Quit if all operands are not constants.
45195     return SDValue();
45196 
45197   if (C->getZExtValue() == 1) {
45198     needOppositeCond = !needOppositeCond;
45199     checkAgainstTrue = true;
45200   } else if (C->getZExtValue() != 0)
45201     // Quit if the constant is neither 0 or 1.
45202     return SDValue();
45203 
45204   bool truncatedToBoolWithAnd = false;
45205   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
45206   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
45207          SetCC.getOpcode() == ISD::TRUNCATE ||
45208          SetCC.getOpcode() == ISD::AND) {
45209     if (SetCC.getOpcode() == ISD::AND) {
45210       int OpIdx = -1;
45211       if (isOneConstant(SetCC.getOperand(0)))
45212         OpIdx = 1;
45213       if (isOneConstant(SetCC.getOperand(1)))
45214         OpIdx = 0;
45215       if (OpIdx < 0)
45216         break;
45217       SetCC = SetCC.getOperand(OpIdx);
45218       truncatedToBoolWithAnd = true;
45219     } else
45220       SetCC = SetCC.getOperand(0);
45221   }
45222 
45223   switch (SetCC.getOpcode()) {
45224   case X86ISD::SETCC_CARRY:
45225     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
45226     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
45227     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
45228     // truncated to i1 using 'and'.
45229     if (checkAgainstTrue && !truncatedToBoolWithAnd)
45230       break;
45231     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
45232            "Invalid use of SETCC_CARRY!");
45233     LLVM_FALLTHROUGH;
45234   case X86ISD::SETCC:
45235     // Set the condition code or opposite one if necessary.
45236     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
45237     if (needOppositeCond)
45238       CC = X86::GetOppositeBranchCondition(CC);
45239     return SetCC.getOperand(1);
45240   case X86ISD::CMOV: {
45241     // Check whether false/true value has canonical one, i.e. 0 or 1.
45242     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
45243     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
45244     // Quit if true value is not a constant.
45245     if (!TVal)
45246       return SDValue();
45247     // Quit if false value is not a constant.
45248     if (!FVal) {
45249       SDValue Op = SetCC.getOperand(0);
45250       // Skip 'zext' or 'trunc' node.
45251       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
45252           Op.getOpcode() == ISD::TRUNCATE)
45253         Op = Op.getOperand(0);
45254       // A special case for rdrand/rdseed, where 0 is set if false cond is
45255       // found.
45256       if ((Op.getOpcode() != X86ISD::RDRAND &&
45257            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
45258         return SDValue();
45259     }
45260     // Quit if false value is not the constant 0 or 1.
45261     bool FValIsFalse = true;
45262     if (FVal && FVal->getZExtValue() != 0) {
45263       if (FVal->getZExtValue() != 1)
45264         return SDValue();
45265       // If FVal is 1, opposite cond is needed.
45266       needOppositeCond = !needOppositeCond;
45267       FValIsFalse = false;
45268     }
45269     // Quit if TVal is not the constant opposite of FVal.
45270     if (FValIsFalse && TVal->getZExtValue() != 1)
45271       return SDValue();
45272     if (!FValIsFalse && TVal->getZExtValue() != 0)
45273       return SDValue();
45274     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
45275     if (needOppositeCond)
45276       CC = X86::GetOppositeBranchCondition(CC);
45277     return SetCC.getOperand(3);
45278   }
45279   }
45280 
45281   return SDValue();
45282 }
45283 
45284 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
45285 /// Match:
45286 ///   (X86or (X86setcc) (X86setcc))
45287 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
45288 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
45289                                            X86::CondCode &CC1, SDValue &Flags,
45290                                            bool &isAnd) {
45291   if (Cond->getOpcode() == X86ISD::CMP) {
45292     if (!isNullConstant(Cond->getOperand(1)))
45293       return false;
45294 
45295     Cond = Cond->getOperand(0);
45296   }
45297 
45298   isAnd = false;
45299 
45300   SDValue SetCC0, SetCC1;
45301   switch (Cond->getOpcode()) {
45302   default: return false;
45303   case ISD::AND:
45304   case X86ISD::AND:
45305     isAnd = true;
45306     LLVM_FALLTHROUGH;
45307   case ISD::OR:
45308   case X86ISD::OR:
45309     SetCC0 = Cond->getOperand(0);
45310     SetCC1 = Cond->getOperand(1);
45311     break;
45312   };
45313 
45314   // Make sure we have SETCC nodes, using the same flags value.
45315   if (SetCC0.getOpcode() != X86ISD::SETCC ||
45316       SetCC1.getOpcode() != X86ISD::SETCC ||
45317       SetCC0->getOperand(1) != SetCC1->getOperand(1))
45318     return false;
45319 
45320   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
45321   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
45322   Flags = SetCC0->getOperand(1);
45323   return true;
45324 }
45325 
45326 // When legalizing carry, we create carries via add X, -1
45327 // If that comes from an actual carry, via setcc, we use the
45328 // carry directly.
45329 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
45330   if (EFLAGS.getOpcode() == X86ISD::ADD) {
45331     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
45332       bool FoundAndLSB = false;
45333       SDValue Carry = EFLAGS.getOperand(0);
45334       while (Carry.getOpcode() == ISD::TRUNCATE ||
45335              Carry.getOpcode() == ISD::ZERO_EXTEND ||
45336              (Carry.getOpcode() == ISD::AND &&
45337               isOneConstant(Carry.getOperand(1)))) {
45338         FoundAndLSB |= Carry.getOpcode() == ISD::AND;
45339         Carry = Carry.getOperand(0);
45340       }
45341       if (Carry.getOpcode() == X86ISD::SETCC ||
45342           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
45343         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
45344         uint64_t CarryCC = Carry.getConstantOperandVal(0);
45345         SDValue CarryOp1 = Carry.getOperand(1);
45346         if (CarryCC == X86::COND_B)
45347           return CarryOp1;
45348         if (CarryCC == X86::COND_A) {
45349           // Try to convert COND_A into COND_B in an attempt to facilitate
45350           // materializing "setb reg".
45351           //
45352           // Do not flip "e > c", where "c" is a constant, because Cmp
45353           // instruction cannot take an immediate as its first operand.
45354           //
45355           if (CarryOp1.getOpcode() == X86ISD::SUB &&
45356               CarryOp1.getNode()->hasOneUse() &&
45357               CarryOp1.getValueType().isInteger() &&
45358               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
45359             SDValue SubCommute =
45360                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
45361                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
45362             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
45363           }
45364         }
45365         // If this is a check of the z flag of an add with 1, switch to the
45366         // C flag.
45367         if (CarryCC == X86::COND_E &&
45368             CarryOp1.getOpcode() == X86ISD::ADD &&
45369             isOneConstant(CarryOp1.getOperand(1)))
45370           return CarryOp1;
45371       } else if (FoundAndLSB) {
45372         SDLoc DL(Carry);
45373         SDValue BitNo = DAG.getConstant(0, DL, Carry.getValueType());
45374         if (Carry.getOpcode() == ISD::SRL) {
45375           BitNo = Carry.getOperand(1);
45376           Carry = Carry.getOperand(0);
45377         }
45378         return getBT(Carry, BitNo, DL, DAG);
45379       }
45380     }
45381   }
45382 
45383   return SDValue();
45384 }
45385 
45386 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
45387 /// to avoid the inversion.
45388 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
45389                               SelectionDAG &DAG,
45390                               const X86Subtarget &Subtarget) {
45391   // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
45392   if (EFLAGS.getOpcode() != X86ISD::PTEST &&
45393       EFLAGS.getOpcode() != X86ISD::TESTP)
45394     return SDValue();
45395 
45396   // PTEST/TESTP sets EFLAGS as:
45397   // TESTZ: ZF = (Op0 & Op1) == 0
45398   // TESTC: CF = (~Op0 & Op1) == 0
45399   // TESTNZC: ZF == 0 && CF == 0
45400   EVT VT = EFLAGS.getValueType();
45401   SDValue Op0 = EFLAGS.getOperand(0);
45402   SDValue Op1 = EFLAGS.getOperand(1);
45403   EVT OpVT = Op0.getValueType();
45404 
45405   // TEST*(~X,Y) == TEST*(X,Y)
45406   if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
45407     X86::CondCode InvCC;
45408     switch (CC) {
45409     case X86::COND_B:
45410       // testc -> testz.
45411       InvCC = X86::COND_E;
45412       break;
45413     case X86::COND_AE:
45414       // !testc -> !testz.
45415       InvCC = X86::COND_NE;
45416       break;
45417     case X86::COND_E:
45418       // testz -> testc.
45419       InvCC = X86::COND_B;
45420       break;
45421     case X86::COND_NE:
45422       // !testz -> !testc.
45423       InvCC = X86::COND_AE;
45424       break;
45425     case X86::COND_A:
45426     case X86::COND_BE:
45427       // testnzc -> testnzc (no change).
45428       InvCC = CC;
45429       break;
45430     default:
45431       InvCC = X86::COND_INVALID;
45432       break;
45433     }
45434 
45435     if (InvCC != X86::COND_INVALID) {
45436       CC = InvCC;
45437       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45438                          DAG.getBitcast(OpVT, NotOp0), Op1);
45439     }
45440   }
45441 
45442   if (CC == X86::COND_E || CC == X86::COND_NE) {
45443     // TESTZ(X,~Y) == TESTC(Y,X)
45444     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
45445       CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
45446       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45447                          DAG.getBitcast(OpVT, NotOp1), Op0);
45448     }
45449 
45450     if (Op0 == Op1) {
45451       SDValue BC = peekThroughBitcasts(Op0);
45452       EVT BCVT = BC.getValueType();
45453       assert(BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
45454              "Unexpected vector type");
45455 
45456       // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
45457       if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
45458         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45459                            DAG.getBitcast(OpVT, BC.getOperand(0)),
45460                            DAG.getBitcast(OpVT, BC.getOperand(1)));
45461       }
45462 
45463       // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
45464       if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
45465         CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
45466         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45467                            DAG.getBitcast(OpVT, BC.getOperand(0)),
45468                            DAG.getBitcast(OpVT, BC.getOperand(1)));
45469       }
45470 
45471       // If every element is an all-sign value, see if we can use MOVMSK to
45472       // more efficiently extract the sign bits and compare that.
45473       // TODO: Handle TESTC with comparison inversion.
45474       // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
45475       // MOVMSK combines to make sure its never worse than PTEST?
45476       unsigned EltBits = BCVT.getScalarSizeInBits();
45477       if (DAG.ComputeNumSignBits(BC) == EltBits) {
45478         assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
45479         APInt SignMask = APInt::getSignMask(EltBits);
45480         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45481         if (SDValue Res =
45482                 TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
45483           // For vXi16 cases we need to use pmovmksb and extract every other
45484           // sign bit.
45485           SDLoc DL(EFLAGS);
45486           if (EltBits == 16) {
45487             MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
45488             Res = DAG.getBitcast(MovmskVT, Res);
45489             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
45490             Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
45491                               DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
45492           } else {
45493             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
45494           }
45495           return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
45496                              DAG.getConstant(0, DL, MVT::i32));
45497         }
45498       }
45499     }
45500 
45501     // TESTZ(-1,X) == TESTZ(X,X)
45502     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
45503       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
45504 
45505     // TESTZ(X,-1) == TESTZ(X,X)
45506     if (ISD::isBuildVectorAllOnes(Op1.getNode()))
45507       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
45508 
45509     // TESTZ(OR(LO(X),HI(X)),OR(LO(Y),HI(Y))) -> TESTZ(X,Y)
45510     // TODO: Add COND_NE handling?
45511     if (CC == X86::COND_E && OpVT.is128BitVector() && Subtarget.hasAVX()) {
45512       SDValue Src0 = peekThroughBitcasts(Op0);
45513       SDValue Src1 = peekThroughBitcasts(Op1);
45514       if (Src0.getOpcode() == ISD::OR && Src1.getOpcode() == ISD::OR) {
45515         Src0 = getSplitVectorSrc(peekThroughBitcasts(Src0.getOperand(0)),
45516                                  peekThroughBitcasts(Src0.getOperand(1)), true);
45517         Src1 = getSplitVectorSrc(peekThroughBitcasts(Src1.getOperand(0)),
45518                                  peekThroughBitcasts(Src1.getOperand(1)), true);
45519         if (Src0 && Src1)
45520           return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45521                              DAG.getBitcast(MVT::v4i64, Src0),
45522                              DAG.getBitcast(MVT::v4i64, Src1));
45523       }
45524     }
45525   }
45526 
45527   return SDValue();
45528 }
45529 
45530 // Attempt to simplify the MOVMSK input based on the comparison type.
45531 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
45532                                   SelectionDAG &DAG,
45533                                   const X86Subtarget &Subtarget) {
45534   // Handle eq/ne against zero (any_of).
45535   // Handle eq/ne against -1 (all_of).
45536   if (!(CC == X86::COND_E || CC == X86::COND_NE))
45537     return SDValue();
45538   if (EFLAGS.getValueType() != MVT::i32)
45539     return SDValue();
45540   unsigned CmpOpcode = EFLAGS.getOpcode();
45541   if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
45542     return SDValue();
45543   auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
45544   if (!CmpConstant)
45545     return SDValue();
45546   const APInt &CmpVal = CmpConstant->getAPIntValue();
45547 
45548   SDValue CmpOp = EFLAGS.getOperand(0);
45549   unsigned CmpBits = CmpOp.getValueSizeInBits();
45550   assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
45551 
45552   // Peek through any truncate.
45553   if (CmpOp.getOpcode() == ISD::TRUNCATE)
45554     CmpOp = CmpOp.getOperand(0);
45555 
45556   // Bail if we don't find a MOVMSK.
45557   if (CmpOp.getOpcode() != X86ISD::MOVMSK)
45558     return SDValue();
45559 
45560   SDValue Vec = CmpOp.getOperand(0);
45561   MVT VecVT = Vec.getSimpleValueType();
45562   assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
45563          "Unexpected MOVMSK operand");
45564   unsigned NumElts = VecVT.getVectorNumElements();
45565   unsigned NumEltBits = VecVT.getScalarSizeInBits();
45566 
45567   bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isZero();
45568   bool IsAllOf = (CmpOpcode == X86ISD::SUB || CmpOpcode == X86ISD::CMP) &&
45569                  NumElts <= CmpBits && CmpVal.isMask(NumElts);
45570   if (!IsAnyOf && !IsAllOf)
45571     return SDValue();
45572 
45573   // TODO: Check more combining cases for me.
45574   // Here we check the cmp use number to decide do combining or not.
45575   // Currently we only get 2 tests about combining "MOVMSK(CONCAT(..))"
45576   // and "MOVMSK(PCMPEQ(..))" are fit to use this constraint.
45577   bool IsOneUse = CmpOp.getNode()->hasOneUse();
45578 
45579   // See if we can peek through to a vector with a wider element type, if the
45580   // signbits extend down to all the sub-elements as well.
45581   // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
45582   // potential SimplifyDemandedBits/Elts cases.
45583   // If we looked through a truncate that discard bits, we can't do this
45584   // transform.
45585   // FIXME: We could do this transform for truncates that discarded bits by
45586   // inserting an AND mask between the new MOVMSK and the CMP.
45587   if (Vec.getOpcode() == ISD::BITCAST && NumElts <= CmpBits) {
45588     SDValue BC = peekThroughBitcasts(Vec);
45589     MVT BCVT = BC.getSimpleValueType();
45590     unsigned BCNumElts = BCVT.getVectorNumElements();
45591     unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
45592     if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
45593         BCNumEltBits > NumEltBits &&
45594         DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
45595       SDLoc DL(EFLAGS);
45596       APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : BCNumElts);
45597       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
45598                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
45599                          DAG.getConstant(CmpMask, DL, MVT::i32));
45600     }
45601   }
45602 
45603   // MOVMSK(CONCAT(X,Y)) == 0 ->  MOVMSK(OR(X,Y)).
45604   // MOVMSK(CONCAT(X,Y)) != 0 ->  MOVMSK(OR(X,Y)).
45605   // MOVMSK(CONCAT(X,Y)) == -1 ->  MOVMSK(AND(X,Y)).
45606   // MOVMSK(CONCAT(X,Y)) != -1 ->  MOVMSK(AND(X,Y)).
45607   if (VecVT.is256BitVector() && NumElts <= CmpBits && IsOneUse) {
45608     SmallVector<SDValue> Ops;
45609     if (collectConcatOps(peekThroughBitcasts(Vec).getNode(), Ops, DAG) &&
45610         Ops.size() == 2) {
45611       SDLoc DL(EFLAGS);
45612       EVT SubVT = Ops[0].getValueType().changeTypeToInteger();
45613       APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : NumElts / 2);
45614       SDValue V = DAG.getNode(IsAnyOf ? ISD::OR : ISD::AND, DL, SubVT,
45615                               DAG.getBitcast(SubVT, Ops[0]),
45616                               DAG.getBitcast(SubVT, Ops[1]));
45617       V = DAG.getBitcast(VecVT.getHalfNumVectorElementsVT(), V);
45618       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
45619                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V),
45620                          DAG.getConstant(CmpMask, DL, MVT::i32));
45621     }
45622   }
45623 
45624   // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
45625   // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
45626   // MOVMSK(PCMPEQ(X,Y)) == -1 -> PTESTZ(SUB(X,Y),SUB(X,Y)).
45627   // MOVMSK(PCMPEQ(X,Y)) != -1 -> !PTESTZ(SUB(X,Y),SUB(X,Y)).
45628   if (IsAllOf && Subtarget.hasSSE41() && IsOneUse) {
45629     MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
45630     SDValue BC = peekThroughBitcasts(Vec);
45631     // Ensure MOVMSK was testing every signbit of BC.
45632     if (BC.getValueType().getVectorNumElements() <= NumElts) {
45633       if (BC.getOpcode() == X86ISD::PCMPEQ) {
45634         SDValue V = DAG.getNode(ISD::SUB, SDLoc(BC), BC.getValueType(),
45635                                 BC.getOperand(0), BC.getOperand(1));
45636         V = DAG.getBitcast(TestVT, V);
45637         return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
45638       }
45639       // Check for 256-bit split vector cases.
45640       if (BC.getOpcode() == ISD::AND &&
45641           BC.getOperand(0).getOpcode() == X86ISD::PCMPEQ &&
45642           BC.getOperand(1).getOpcode() == X86ISD::PCMPEQ) {
45643         SDValue LHS = BC.getOperand(0);
45644         SDValue RHS = BC.getOperand(1);
45645         LHS = DAG.getNode(ISD::SUB, SDLoc(LHS), LHS.getValueType(),
45646                           LHS.getOperand(0), LHS.getOperand(1));
45647         RHS = DAG.getNode(ISD::SUB, SDLoc(RHS), RHS.getValueType(),
45648                           RHS.getOperand(0), RHS.getOperand(1));
45649         LHS = DAG.getBitcast(TestVT, LHS);
45650         RHS = DAG.getBitcast(TestVT, RHS);
45651         SDValue V = DAG.getNode(ISD::OR, SDLoc(EFLAGS), TestVT, LHS, RHS);
45652         return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
45653       }
45654     }
45655   }
45656 
45657   // See if we can avoid a PACKSS by calling MOVMSK on the sources.
45658   // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
45659   // sign bits prior to the comparison with zero unless we know that
45660   // the vXi16 splats the sign bit down to the lower i8 half.
45661   // TODO: Handle all_of patterns.
45662   if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
45663     SDValue VecOp0 = Vec.getOperand(0);
45664     SDValue VecOp1 = Vec.getOperand(1);
45665     bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
45666     bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
45667     // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
45668     if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
45669       SDLoc DL(EFLAGS);
45670       SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
45671       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
45672       Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
45673       if (!SignExt0) {
45674         Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
45675                              DAG.getConstant(0xAAAA, DL, MVT::i16));
45676       }
45677       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
45678                          DAG.getConstant(0, DL, MVT::i16));
45679     }
45680     // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
45681     // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
45682     if (CmpBits >= 16 && Subtarget.hasInt256() &&
45683         (IsAnyOf || (SignExt0 && SignExt1))) {
45684       if (SDValue Src = getSplitVectorSrc(VecOp0, VecOp1, true)) {
45685         SDLoc DL(EFLAGS);
45686         SDValue Result = peekThroughBitcasts(Src);
45687         if (IsAllOf && Result.getOpcode() == X86ISD::PCMPEQ &&
45688             Result.getValueType().getVectorNumElements() <= NumElts) {
45689           SDValue V = DAG.getNode(ISD::SUB, DL, Result.getValueType(),
45690                                   Result.getOperand(0), Result.getOperand(1));
45691           V = DAG.getBitcast(MVT::v4i64, V);
45692           return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
45693         }
45694         Result = DAG.getBitcast(MVT::v32i8, Result);
45695         Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
45696         unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
45697         if (!SignExt0 || !SignExt1) {
45698           assert(IsAnyOf &&
45699                  "Only perform v16i16 signmasks for any_of patterns");
45700           Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
45701                                DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
45702         }
45703         return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
45704                            DAG.getConstant(CmpMask, DL, MVT::i32));
45705       }
45706     }
45707   }
45708 
45709   // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
45710   SmallVector<int, 32> ShuffleMask;
45711   SmallVector<SDValue, 2> ShuffleInputs;
45712   if (NumElts <= CmpBits &&
45713       getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
45714                              ShuffleMask, DAG) &&
45715       ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
45716       ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits()) {
45717     unsigned NumShuffleElts = ShuffleMask.size();
45718     APInt DemandedElts = APInt::getZero(NumShuffleElts);
45719     for (int M : ShuffleMask) {
45720       assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index");
45721       DemandedElts.setBit(M);
45722     }
45723     if (DemandedElts.isAllOnes()) {
45724       SDLoc DL(EFLAGS);
45725       SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
45726       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
45727       Result =
45728           DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
45729       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
45730                          EFLAGS.getOperand(1));
45731     }
45732   }
45733 
45734   return SDValue();
45735 }
45736 
45737 /// Optimize an EFLAGS definition used according to the condition code \p CC
45738 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
45739 /// uses of chain values.
45740 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
45741                                   SelectionDAG &DAG,
45742                                   const X86Subtarget &Subtarget) {
45743   if (CC == X86::COND_B)
45744     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
45745       return Flags;
45746 
45747   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
45748     return R;
45749 
45750   if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
45751     return R;
45752 
45753   if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
45754     return R;
45755 
45756   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
45757 }
45758 
45759 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
45760 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
45761                            TargetLowering::DAGCombinerInfo &DCI,
45762                            const X86Subtarget &Subtarget) {
45763   SDLoc DL(N);
45764 
45765   SDValue FalseOp = N->getOperand(0);
45766   SDValue TrueOp = N->getOperand(1);
45767   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
45768   SDValue Cond = N->getOperand(3);
45769 
45770   // cmov X, X, ?, ? --> X
45771   if (TrueOp == FalseOp)
45772     return TrueOp;
45773 
45774   // Try to simplify the EFLAGS and condition code operands.
45775   // We can't always do this as FCMOV only supports a subset of X86 cond.
45776   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
45777     if (!(FalseOp.getValueType() == MVT::f80 ||
45778           (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
45779           (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
45780         !Subtarget.canUseCMOV() || hasFPCMov(CC)) {
45781       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
45782                        Flags};
45783       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
45784     }
45785   }
45786 
45787   // If this is a select between two integer constants, try to do some
45788   // optimizations.  Note that the operands are ordered the opposite of SELECT
45789   // operands.
45790   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
45791     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
45792       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
45793       // larger than FalseC (the false value).
45794       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
45795         CC = X86::GetOppositeBranchCondition(CC);
45796         std::swap(TrueC, FalseC);
45797         std::swap(TrueOp, FalseOp);
45798       }
45799 
45800       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
45801       // This is efficient for any integer data type (including i8/i16) and
45802       // shift amount.
45803       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
45804         Cond = getSETCC(CC, Cond, DL, DAG);
45805 
45806         // Zero extend the condition if needed.
45807         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
45808 
45809         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
45810         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
45811                            DAG.getConstant(ShAmt, DL, MVT::i8));
45812         return Cond;
45813       }
45814 
45815       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
45816       // for any integer data type, including i8/i16.
45817       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
45818         Cond = getSETCC(CC, Cond, DL, DAG);
45819 
45820         // Zero extend the condition if needed.
45821         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
45822                            FalseC->getValueType(0), Cond);
45823         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
45824                            SDValue(FalseC, 0));
45825         return Cond;
45826       }
45827 
45828       // Optimize cases that will turn into an LEA instruction.  This requires
45829       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
45830       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
45831         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
45832         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
45833                "Implicit constant truncation");
45834 
45835         bool isFastMultiplier = false;
45836         if (Diff.ult(10)) {
45837           switch (Diff.getZExtValue()) {
45838           default: break;
45839           case 1:  // result = add base, cond
45840           case 2:  // result = lea base(    , cond*2)
45841           case 3:  // result = lea base(cond, cond*2)
45842           case 4:  // result = lea base(    , cond*4)
45843           case 5:  // result = lea base(cond, cond*4)
45844           case 8:  // result = lea base(    , cond*8)
45845           case 9:  // result = lea base(cond, cond*8)
45846             isFastMultiplier = true;
45847             break;
45848           }
45849         }
45850 
45851         if (isFastMultiplier) {
45852           Cond = getSETCC(CC, Cond, DL ,DAG);
45853           // Zero extend the condition if needed.
45854           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
45855                              Cond);
45856           // Scale the condition by the difference.
45857           if (Diff != 1)
45858             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
45859                                DAG.getConstant(Diff, DL, Cond.getValueType()));
45860 
45861           // Add the base if non-zero.
45862           if (FalseC->getAPIntValue() != 0)
45863             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
45864                                SDValue(FalseC, 0));
45865           return Cond;
45866         }
45867       }
45868     }
45869   }
45870 
45871   // Handle these cases:
45872   //   (select (x != c), e, c) -> select (x != c), e, x),
45873   //   (select (x == c), c, e) -> select (x == c), x, e)
45874   // where the c is an integer constant, and the "select" is the combination
45875   // of CMOV and CMP.
45876   //
45877   // The rationale for this change is that the conditional-move from a constant
45878   // needs two instructions, however, conditional-move from a register needs
45879   // only one instruction.
45880   //
45881   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
45882   //  some instruction-combining opportunities. This opt needs to be
45883   //  postponed as late as possible.
45884   //
45885   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
45886     // the DCI.xxxx conditions are provided to postpone the optimization as
45887     // late as possible.
45888 
45889     ConstantSDNode *CmpAgainst = nullptr;
45890     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
45891         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
45892         !isa<ConstantSDNode>(Cond.getOperand(0))) {
45893 
45894       if (CC == X86::COND_NE &&
45895           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
45896         CC = X86::GetOppositeBranchCondition(CC);
45897         std::swap(TrueOp, FalseOp);
45898       }
45899 
45900       if (CC == X86::COND_E &&
45901           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
45902         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
45903                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
45904         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
45905       }
45906     }
45907   }
45908 
45909   // Fold and/or of setcc's to double CMOV:
45910   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
45911   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
45912   //
45913   // This combine lets us generate:
45914   //   cmovcc1 (jcc1 if we don't have CMOV)
45915   //   cmovcc2 (same)
45916   // instead of:
45917   //   setcc1
45918   //   setcc2
45919   //   and/or
45920   //   cmovne (jne if we don't have CMOV)
45921   // When we can't use the CMOV instruction, it might increase branch
45922   // mispredicts.
45923   // When we can use CMOV, or when there is no mispredict, this improves
45924   // throughput and reduces register pressure.
45925   //
45926   if (CC == X86::COND_NE) {
45927     SDValue Flags;
45928     X86::CondCode CC0, CC1;
45929     bool isAndSetCC;
45930     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
45931       if (isAndSetCC) {
45932         std::swap(FalseOp, TrueOp);
45933         CC0 = X86::GetOppositeBranchCondition(CC0);
45934         CC1 = X86::GetOppositeBranchCondition(CC1);
45935       }
45936 
45937       SDValue LOps[] = {FalseOp, TrueOp,
45938                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
45939       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
45940       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
45941                        Flags};
45942       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
45943       return CMOV;
45944     }
45945   }
45946 
45947   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
45948   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
45949   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
45950   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
45951   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
45952       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
45953     SDValue Add = TrueOp;
45954     SDValue Const = FalseOp;
45955     // Canonicalize the condition code for easier matching and output.
45956     if (CC == X86::COND_E)
45957       std::swap(Add, Const);
45958 
45959     // We might have replaced the constant in the cmov with the LHS of the
45960     // compare. If so change it to the RHS of the compare.
45961     if (Const == Cond.getOperand(0))
45962       Const = Cond.getOperand(1);
45963 
45964     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
45965     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
45966         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
45967         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
45968          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
45969         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
45970       EVT VT = N->getValueType(0);
45971       // This should constant fold.
45972       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
45973       SDValue CMov =
45974           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
45975                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
45976       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
45977     }
45978   }
45979 
45980   return SDValue();
45981 }
45982 
45983 /// Different mul shrinking modes.
45984 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
45985 
45986 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
45987   EVT VT = N->getOperand(0).getValueType();
45988   if (VT.getScalarSizeInBits() != 32)
45989     return false;
45990 
45991   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
45992   unsigned SignBits[2] = {1, 1};
45993   bool IsPositive[2] = {false, false};
45994   for (unsigned i = 0; i < 2; i++) {
45995     SDValue Opd = N->getOperand(i);
45996 
45997     SignBits[i] = DAG.ComputeNumSignBits(Opd);
45998     IsPositive[i] = DAG.SignBitIsZero(Opd);
45999   }
46000 
46001   bool AllPositive = IsPositive[0] && IsPositive[1];
46002   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
46003   // When ranges are from -128 ~ 127, use MULS8 mode.
46004   if (MinSignBits >= 25)
46005     Mode = ShrinkMode::MULS8;
46006   // When ranges are from 0 ~ 255, use MULU8 mode.
46007   else if (AllPositive && MinSignBits >= 24)
46008     Mode = ShrinkMode::MULU8;
46009   // When ranges are from -32768 ~ 32767, use MULS16 mode.
46010   else if (MinSignBits >= 17)
46011     Mode = ShrinkMode::MULS16;
46012   // When ranges are from 0 ~ 65535, use MULU16 mode.
46013   else if (AllPositive && MinSignBits >= 16)
46014     Mode = ShrinkMode::MULU16;
46015   else
46016     return false;
46017   return true;
46018 }
46019 
46020 /// When the operands of vector mul are extended from smaller size values,
46021 /// like i8 and i16, the type of mul may be shrinked to generate more
46022 /// efficient code. Two typical patterns are handled:
46023 /// Pattern1:
46024 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
46025 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
46026 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
46027 ///     %5 = mul <N x i32> %2, %4
46028 ///
46029 /// Pattern2:
46030 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
46031 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
46032 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
46033 ///     %5 = mul <N x i32> %2, %4
46034 ///
46035 /// There are four mul shrinking modes:
46036 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
46037 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
46038 /// generate pmullw+sext32 for it (MULS8 mode).
46039 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
46040 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
46041 /// generate pmullw+zext32 for it (MULU8 mode).
46042 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
46043 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
46044 /// generate pmullw+pmulhw for it (MULS16 mode).
46045 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
46046 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
46047 /// generate pmullw+pmulhuw for it (MULU16 mode).
46048 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
46049                                const X86Subtarget &Subtarget) {
46050   // Check for legality
46051   // pmullw/pmulhw are not supported by SSE.
46052   if (!Subtarget.hasSSE2())
46053     return SDValue();
46054 
46055   // Check for profitability
46056   // pmulld is supported since SSE41. It is better to use pmulld
46057   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
46058   // the expansion.
46059   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
46060   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
46061     return SDValue();
46062 
46063   ShrinkMode Mode;
46064   if (!canReduceVMulWidth(N, DAG, Mode))
46065     return SDValue();
46066 
46067   SDLoc DL(N);
46068   SDValue N0 = N->getOperand(0);
46069   SDValue N1 = N->getOperand(1);
46070   EVT VT = N->getOperand(0).getValueType();
46071   unsigned NumElts = VT.getVectorNumElements();
46072   if ((NumElts % 2) != 0)
46073     return SDValue();
46074 
46075   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
46076 
46077   // Shrink the operands of mul.
46078   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
46079   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
46080 
46081   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
46082   // lower part is needed.
46083   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
46084   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
46085     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
46086                                                    : ISD::SIGN_EXTEND,
46087                        DL, VT, MulLo);
46088 
46089   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
46090   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
46091   // the higher part is also needed.
46092   SDValue MulHi =
46093       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
46094                   ReducedVT, NewN0, NewN1);
46095 
46096   // Repack the lower part and higher part result of mul into a wider
46097   // result.
46098   // Generate shuffle functioning as punpcklwd.
46099   SmallVector<int, 16> ShuffleMask(NumElts);
46100   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
46101     ShuffleMask[2 * i] = i;
46102     ShuffleMask[2 * i + 1] = i + NumElts;
46103   }
46104   SDValue ResLo =
46105       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
46106   ResLo = DAG.getBitcast(ResVT, ResLo);
46107   // Generate shuffle functioning as punpckhwd.
46108   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
46109     ShuffleMask[2 * i] = i + NumElts / 2;
46110     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
46111   }
46112   SDValue ResHi =
46113       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
46114   ResHi = DAG.getBitcast(ResVT, ResHi);
46115   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
46116 }
46117 
46118 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
46119                                  EVT VT, const SDLoc &DL) {
46120 
46121   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
46122     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46123                                  DAG.getConstant(Mult, DL, VT));
46124     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
46125                          DAG.getConstant(Shift, DL, MVT::i8));
46126     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
46127                          N->getOperand(0));
46128     return Result;
46129   };
46130 
46131   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
46132     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46133                                  DAG.getConstant(Mul1, DL, VT));
46134     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
46135                          DAG.getConstant(Mul2, DL, VT));
46136     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
46137                          N->getOperand(0));
46138     return Result;
46139   };
46140 
46141   switch (MulAmt) {
46142   default:
46143     break;
46144   case 11:
46145     // mul x, 11 => add ((shl (mul x, 5), 1), x)
46146     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
46147   case 21:
46148     // mul x, 21 => add ((shl (mul x, 5), 2), x)
46149     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
46150   case 41:
46151     // mul x, 41 => add ((shl (mul x, 5), 3), x)
46152     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
46153   case 22:
46154     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
46155     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
46156                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
46157   case 19:
46158     // mul x, 19 => add ((shl (mul x, 9), 1), x)
46159     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
46160   case 37:
46161     // mul x, 37 => add ((shl (mul x, 9), 2), x)
46162     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
46163   case 73:
46164     // mul x, 73 => add ((shl (mul x, 9), 3), x)
46165     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
46166   case 13:
46167     // mul x, 13 => add ((shl (mul x, 3), 2), x)
46168     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
46169   case 23:
46170     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
46171     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
46172   case 26:
46173     // mul x, 26 => add ((mul (mul x, 5), 5), x)
46174     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
46175   case 28:
46176     // mul x, 28 => add ((mul (mul x, 9), 3), x)
46177     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
46178   case 29:
46179     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
46180     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
46181                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
46182   }
46183 
46184   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
46185   // by a single LEA.
46186   // First check if this a sum of two power of 2s because that's easy. Then
46187   // count how many zeros are up to the first bit.
46188   // TODO: We can do this even without LEA at a cost of two shifts and an add.
46189   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
46190     unsigned ScaleShift = countTrailingZeros(MulAmt);
46191     if (ScaleShift >= 1 && ScaleShift < 4) {
46192       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
46193       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46194                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
46195       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46196                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
46197       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
46198     }
46199   }
46200 
46201   return SDValue();
46202 }
46203 
46204 // If the upper 17 bits of either element are zero and the other element are
46205 // zero/sign bits then we can use PMADDWD, which is always at least as quick as
46206 // PMULLD, except on KNL.
46207 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
46208                                    const X86Subtarget &Subtarget) {
46209   if (!Subtarget.hasSSE2())
46210     return SDValue();
46211 
46212   if (Subtarget.isPMADDWDSlow())
46213     return SDValue();
46214 
46215   EVT VT = N->getValueType(0);
46216 
46217   // Only support vXi32 vectors.
46218   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
46219     return SDValue();
46220 
46221   // Make sure the type is legal or can split/widen to a legal type.
46222   // With AVX512 but without BWI, we would need to split v32i16.
46223   unsigned NumElts = VT.getVectorNumElements();
46224   if (NumElts == 1 || !isPowerOf2_32(NumElts))
46225     return SDValue();
46226 
46227   // With AVX512 but without BWI, we would need to split v32i16.
46228   if (32 <= (2 * NumElts) && Subtarget.hasAVX512() && !Subtarget.hasBWI())
46229     return SDValue();
46230 
46231   SDValue N0 = N->getOperand(0);
46232   SDValue N1 = N->getOperand(1);
46233 
46234   // If we are zero/sign extending two steps without SSE4.1, its better to
46235   // reduce the vmul width instead.
46236   if (!Subtarget.hasSSE41() &&
46237       (((N0.getOpcode() == ISD::ZERO_EXTEND &&
46238          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
46239         (N1.getOpcode() == ISD::ZERO_EXTEND &&
46240          N1.getOperand(0).getScalarValueSizeInBits() <= 8)) ||
46241        ((N0.getOpcode() == ISD::SIGN_EXTEND &&
46242          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
46243         (N1.getOpcode() == ISD::SIGN_EXTEND &&
46244          N1.getOperand(0).getScalarValueSizeInBits() <= 8))))
46245     return SDValue();
46246 
46247   // If we are sign extending a wide vector without SSE4.1, its better to reduce
46248   // the vmul width instead.
46249   if (!Subtarget.hasSSE41() &&
46250       (N0.getOpcode() == ISD::SIGN_EXTEND &&
46251        N0.getOperand(0).getValueSizeInBits() > 128) &&
46252       (N1.getOpcode() == ISD::SIGN_EXTEND &&
46253        N1.getOperand(0).getValueSizeInBits() > 128))
46254     return SDValue();
46255 
46256   // Sign bits must extend down to the lowest i16.
46257   if (DAG.ComputeMaxSignificantBits(N1) > 16 ||
46258       DAG.ComputeMaxSignificantBits(N0) > 16)
46259     return SDValue();
46260 
46261   // At least one of the elements must be zero in the upper 17 bits, or can be
46262   // safely made zero without altering the final result.
46263   auto GetZeroableOp = [&](SDValue Op) {
46264     APInt Mask17 = APInt::getHighBitsSet(32, 17);
46265     if (DAG.MaskedValueIsZero(Op, Mask17))
46266       return Op;
46267     // Mask off upper 16-bits of sign-extended constants.
46268     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()))
46269       return DAG.getNode(ISD::AND, SDLoc(N), VT, Op,
46270                          DAG.getConstant(0xFFFF, SDLoc(N), VT));
46271     if (Op.getOpcode() == ISD::SIGN_EXTEND && N->isOnlyUserOf(Op.getNode())) {
46272       SDValue Src = Op.getOperand(0);
46273       // Convert sext(vXi16) to zext(vXi16).
46274       if (Src.getScalarValueSizeInBits() == 16 && VT.getSizeInBits() <= 128)
46275         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
46276       // Convert sext(vXi8) to zext(vXi16 sext(vXi8)) on pre-SSE41 targets
46277       // which will expand the extension.
46278       if (Src.getScalarValueSizeInBits() < 16 && !Subtarget.hasSSE41()) {
46279         EVT ExtVT = VT.changeVectorElementType(MVT::i16);
46280         Src = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), ExtVT, Src);
46281         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
46282       }
46283     }
46284     // Convert SIGN_EXTEND_VECTOR_INREG to ZEXT_EXTEND_VECTOR_INREG.
46285     if (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG &&
46286         N->isOnlyUserOf(Op.getNode())) {
46287       SDValue Src = Op.getOperand(0);
46288       if (Src.getScalarValueSizeInBits() == 16)
46289         return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(N), VT, Src);
46290     }
46291     // Convert VSRAI(Op, 16) to VSRLI(Op, 16).
46292     if (Op.getOpcode() == X86ISD::VSRAI && Op.getConstantOperandVal(1) == 16 &&
46293         N->isOnlyUserOf(Op.getNode())) {
46294       return DAG.getNode(X86ISD::VSRLI, SDLoc(N), VT, Op.getOperand(0),
46295                          Op.getOperand(1));
46296     }
46297     return SDValue();
46298   };
46299   SDValue ZeroN0 = GetZeroableOp(N0);
46300   SDValue ZeroN1 = GetZeroableOp(N1);
46301   if (!ZeroN0 && !ZeroN1)
46302     return SDValue();
46303   N0 = ZeroN0 ? ZeroN0 : N0;
46304   N1 = ZeroN1 ? ZeroN1 : N1;
46305 
46306   // Use SplitOpsAndApply to handle AVX splitting.
46307   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46308                            ArrayRef<SDValue> Ops) {
46309     MVT ResVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
46310     MVT OpVT = MVT::getVectorVT(MVT::i16, Ops[0].getValueSizeInBits() / 16);
46311     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
46312                        DAG.getBitcast(OpVT, Ops[0]),
46313                        DAG.getBitcast(OpVT, Ops[1]));
46314   };
46315   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {N0, N1},
46316                           PMADDWDBuilder);
46317 }
46318 
46319 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
46320                                   const X86Subtarget &Subtarget) {
46321   if (!Subtarget.hasSSE2())
46322     return SDValue();
46323 
46324   EVT VT = N->getValueType(0);
46325 
46326   // Only support vXi64 vectors.
46327   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
46328       VT.getVectorNumElements() < 2 ||
46329       !isPowerOf2_32(VT.getVectorNumElements()))
46330     return SDValue();
46331 
46332   SDValue N0 = N->getOperand(0);
46333   SDValue N1 = N->getOperand(1);
46334 
46335   // MULDQ returns the 64-bit result of the signed multiplication of the lower
46336   // 32-bits. We can lower with this if the sign bits stretch that far.
46337   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
46338       DAG.ComputeNumSignBits(N1) > 32) {
46339     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46340                             ArrayRef<SDValue> Ops) {
46341       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
46342     };
46343     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
46344                             PMULDQBuilder, /*CheckBWI*/false);
46345   }
46346 
46347   // If the upper bits are zero we can use a single pmuludq.
46348   APInt Mask = APInt::getHighBitsSet(64, 32);
46349   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
46350     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46351                              ArrayRef<SDValue> Ops) {
46352       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
46353     };
46354     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
46355                             PMULUDQBuilder, /*CheckBWI*/false);
46356   }
46357 
46358   return SDValue();
46359 }
46360 
46361 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
46362                           TargetLowering::DAGCombinerInfo &DCI,
46363                           const X86Subtarget &Subtarget) {
46364   EVT VT = N->getValueType(0);
46365 
46366   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
46367     return V;
46368 
46369   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
46370     return V;
46371 
46372   if (DCI.isBeforeLegalize() && VT.isVector())
46373     return reduceVMULWidth(N, DAG, Subtarget);
46374 
46375   // Optimize a single multiply with constant into two operations in order to
46376   // implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
46377   if (!MulConstantOptimization)
46378     return SDValue();
46379 
46380   // An imul is usually smaller than the alternative sequence.
46381   if (DAG.getMachineFunction().getFunction().hasMinSize())
46382     return SDValue();
46383 
46384   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
46385     return SDValue();
46386 
46387   if (VT != MVT::i64 && VT != MVT::i32)
46388     return SDValue();
46389 
46390   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
46391   if (!C)
46392     return SDValue();
46393   if (isPowerOf2_64(C->getZExtValue()))
46394     return SDValue();
46395 
46396   int64_t SignMulAmt = C->getSExtValue();
46397   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
46398   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
46399 
46400   SDLoc DL(N);
46401   if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
46402     SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46403                                  DAG.getConstant(AbsMulAmt, DL, VT));
46404     if (SignMulAmt < 0)
46405       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
46406                            NewMul);
46407 
46408     return NewMul;
46409   }
46410 
46411   uint64_t MulAmt1 = 0;
46412   uint64_t MulAmt2 = 0;
46413   if ((AbsMulAmt % 9) == 0) {
46414     MulAmt1 = 9;
46415     MulAmt2 = AbsMulAmt / 9;
46416   } else if ((AbsMulAmt % 5) == 0) {
46417     MulAmt1 = 5;
46418     MulAmt2 = AbsMulAmt / 5;
46419   } else if ((AbsMulAmt % 3) == 0) {
46420     MulAmt1 = 3;
46421     MulAmt2 = AbsMulAmt / 3;
46422   }
46423 
46424   SDValue NewMul;
46425   // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
46426   if (MulAmt2 &&
46427       (isPowerOf2_64(MulAmt2) ||
46428        (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
46429 
46430     if (isPowerOf2_64(MulAmt2) &&
46431         !(SignMulAmt >= 0 && N->hasOneUse() &&
46432           N->use_begin()->getOpcode() == ISD::ADD))
46433       // If second multiplifer is pow2, issue it first. We want the multiply by
46434       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
46435       // is an add. Only do this for positive multiply amounts since the
46436       // negate would prevent it from being used as an address mode anyway.
46437       std::swap(MulAmt1, MulAmt2);
46438 
46439     if (isPowerOf2_64(MulAmt1))
46440       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46441                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
46442     else
46443       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46444                            DAG.getConstant(MulAmt1, DL, VT));
46445 
46446     if (isPowerOf2_64(MulAmt2))
46447       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
46448                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
46449     else
46450       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
46451                            DAG.getConstant(MulAmt2, DL, VT));
46452 
46453     // Negate the result.
46454     if (SignMulAmt < 0)
46455       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
46456                            NewMul);
46457   } else if (!Subtarget.slowLEA())
46458     NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
46459 
46460   if (!NewMul) {
46461     assert(C->getZExtValue() != 0 &&
46462            C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&
46463            "Both cases that could cause potential overflows should have "
46464            "already been handled.");
46465     if (isPowerOf2_64(AbsMulAmt - 1)) {
46466       // (mul x, 2^N + 1) => (add (shl x, N), x)
46467       NewMul = DAG.getNode(
46468           ISD::ADD, DL, VT, N->getOperand(0),
46469           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46470                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
46471                                       MVT::i8)));
46472       // To negate, subtract the number from zero
46473       if (SignMulAmt < 0)
46474         NewMul = DAG.getNode(ISD::SUB, DL, VT,
46475                              DAG.getConstant(0, DL, VT), NewMul);
46476     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
46477       // (mul x, 2^N - 1) => (sub (shl x, N), x)
46478       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46479                            DAG.getConstant(Log2_64(AbsMulAmt + 1),
46480                                            DL, MVT::i8));
46481       // To negate, reverse the operands of the subtract.
46482       if (SignMulAmt < 0)
46483         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
46484       else
46485         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
46486     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
46487       // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
46488       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46489                            DAG.getConstant(Log2_64(AbsMulAmt - 2),
46490                                            DL, MVT::i8));
46491       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
46492       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
46493     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
46494       // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
46495       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46496                            DAG.getConstant(Log2_64(AbsMulAmt + 2),
46497                                            DL, MVT::i8));
46498       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
46499       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
46500     }
46501   }
46502 
46503   return NewMul;
46504 }
46505 
46506 // Try to form a MULHU or MULHS node by looking for
46507 // (srl (mul ext, ext), 16)
46508 // TODO: This is X86 specific because we want to be able to handle wide types
46509 // before type legalization. But we can only do it if the vector will be
46510 // legalized via widening/splitting. Type legalization can't handle promotion
46511 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
46512 // combiner.
46513 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
46514                                    const X86Subtarget &Subtarget) {
46515   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
46516            "SRL or SRA node is required here!");
46517   SDLoc DL(N);
46518 
46519   if (!Subtarget.hasSSE2())
46520     return SDValue();
46521 
46522   // The operation feeding into the shift must be a multiply.
46523   SDValue ShiftOperand = N->getOperand(0);
46524   if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
46525     return SDValue();
46526 
46527   // Input type should be at least vXi32.
46528   EVT VT = N->getValueType(0);
46529   if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
46530     return SDValue();
46531 
46532   // Need a shift by 16.
46533   APInt ShiftAmt;
46534   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
46535       ShiftAmt != 16)
46536     return SDValue();
46537 
46538   SDValue LHS = ShiftOperand.getOperand(0);
46539   SDValue RHS = ShiftOperand.getOperand(1);
46540 
46541   unsigned ExtOpc = LHS.getOpcode();
46542   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
46543       RHS.getOpcode() != ExtOpc)
46544     return SDValue();
46545 
46546   // Peek through the extends.
46547   LHS = LHS.getOperand(0);
46548   RHS = RHS.getOperand(0);
46549 
46550   // Ensure the input types match.
46551   EVT MulVT = LHS.getValueType();
46552   if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
46553     return SDValue();
46554 
46555   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
46556   SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
46557 
46558   ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
46559   return DAG.getNode(ExtOpc, DL, VT, Mulh);
46560 }
46561 
46562 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
46563   SDValue N0 = N->getOperand(0);
46564   SDValue N1 = N->getOperand(1);
46565   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
46566   EVT VT = N0.getValueType();
46567 
46568   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
46569   // since the result of setcc_c is all zero's or all ones.
46570   if (VT.isInteger() && !VT.isVector() &&
46571       N1C && N0.getOpcode() == ISD::AND &&
46572       N0.getOperand(1).getOpcode() == ISD::Constant) {
46573     SDValue N00 = N0.getOperand(0);
46574     APInt Mask = N0.getConstantOperandAPInt(1);
46575     Mask <<= N1C->getAPIntValue();
46576     bool MaskOK = false;
46577     // We can handle cases concerning bit-widening nodes containing setcc_c if
46578     // we carefully interrogate the mask to make sure we are semantics
46579     // preserving.
46580     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
46581     // of the underlying setcc_c operation if the setcc_c was zero extended.
46582     // Consider the following example:
46583     //   zext(setcc_c)                 -> i32 0x0000FFFF
46584     //   c1                            -> i32 0x0000FFFF
46585     //   c2                            -> i32 0x00000001
46586     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
46587     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
46588     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
46589       MaskOK = true;
46590     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
46591                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
46592       MaskOK = true;
46593     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
46594                 N00.getOpcode() == ISD::ANY_EXTEND) &&
46595                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
46596       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
46597     }
46598     if (MaskOK && Mask != 0) {
46599       SDLoc DL(N);
46600       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
46601     }
46602   }
46603 
46604   // Hardware support for vector shifts is sparse which makes us scalarize the
46605   // vector operations in many cases. Also, on sandybridge ADD is faster than
46606   // shl.
46607   // (shl V, 1) -> add V,V
46608   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
46609     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
46610       assert(N0.getValueType().isVector() && "Invalid vector shift type");
46611       // We shift all of the values by one. In many cases we do not have
46612       // hardware support for this operation. This is better expressed as an ADD
46613       // of two values.
46614       if (N1SplatC->isOne())
46615         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
46616     }
46617 
46618   return SDValue();
46619 }
46620 
46621 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
46622                                            const X86Subtarget &Subtarget) {
46623   SDValue N0 = N->getOperand(0);
46624   SDValue N1 = N->getOperand(1);
46625   EVT VT = N0.getValueType();
46626   unsigned Size = VT.getSizeInBits();
46627 
46628   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
46629     return V;
46630 
46631   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
46632   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
46633   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
46634   // depending on sign of (SarConst - [56,48,32,24,16])
46635 
46636   // sexts in X86 are MOVs. The MOVs have the same code size
46637   // as above SHIFTs (only SHIFT on 1 has lower code size).
46638   // However the MOVs have 2 advantages to a SHIFT:
46639   // 1. MOVs can write to a register that differs from source
46640   // 2. MOVs accept memory operands
46641 
46642   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
46643       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
46644       N0.getOperand(1).getOpcode() != ISD::Constant)
46645     return SDValue();
46646 
46647   SDValue N00 = N0.getOperand(0);
46648   SDValue N01 = N0.getOperand(1);
46649   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
46650   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
46651   EVT CVT = N1.getValueType();
46652 
46653   if (SarConst.isNegative())
46654     return SDValue();
46655 
46656   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
46657     unsigned ShiftSize = SVT.getSizeInBits();
46658     // skipping types without corresponding sext/zext and
46659     // ShlConst that is not one of [56,48,32,24,16]
46660     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
46661       continue;
46662     SDLoc DL(N);
46663     SDValue NN =
46664         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
46665     SarConst = SarConst - (Size - ShiftSize);
46666     if (SarConst == 0)
46667       return NN;
46668     if (SarConst.isNegative())
46669       return DAG.getNode(ISD::SHL, DL, VT, NN,
46670                          DAG.getConstant(-SarConst, DL, CVT));
46671     return DAG.getNode(ISD::SRA, DL, VT, NN,
46672                        DAG.getConstant(SarConst, DL, CVT));
46673   }
46674   return SDValue();
46675 }
46676 
46677 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
46678                                         TargetLowering::DAGCombinerInfo &DCI,
46679                                         const X86Subtarget &Subtarget) {
46680   SDValue N0 = N->getOperand(0);
46681   SDValue N1 = N->getOperand(1);
46682   EVT VT = N0.getValueType();
46683 
46684   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
46685     return V;
46686 
46687   // Only do this on the last DAG combine as it can interfere with other
46688   // combines.
46689   if (!DCI.isAfterLegalizeDAG())
46690     return SDValue();
46691 
46692   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
46693   // TODO: This is a generic DAG combine that became an x86-only combine to
46694   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
46695   // and-not ('andn').
46696   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
46697     return SDValue();
46698 
46699   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
46700   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
46701   if (!ShiftC || !AndC)
46702     return SDValue();
46703 
46704   // If we can shrink the constant mask below 8-bits or 32-bits, then this
46705   // transform should reduce code size. It may also enable secondary transforms
46706   // from improved known-bits analysis or instruction selection.
46707   APInt MaskVal = AndC->getAPIntValue();
46708 
46709   // If this can be matched by a zero extend, don't optimize.
46710   if (MaskVal.isMask()) {
46711     unsigned TO = MaskVal.countTrailingOnes();
46712     if (TO >= 8 && isPowerOf2_32(TO))
46713       return SDValue();
46714   }
46715 
46716   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
46717   unsigned OldMaskSize = MaskVal.getMinSignedBits();
46718   unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
46719   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
46720       (OldMaskSize > 32 && NewMaskSize <= 32)) {
46721     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
46722     SDLoc DL(N);
46723     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
46724     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
46725     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
46726   }
46727   return SDValue();
46728 }
46729 
46730 static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
46731                                          const X86Subtarget &Subtarget) {
46732   unsigned Opcode = N->getOpcode();
46733   assert(isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode");
46734 
46735   SDLoc DL(N);
46736   EVT VT = N->getValueType(0);
46737   SDValue N0 = N->getOperand(0);
46738   SDValue N1 = N->getOperand(1);
46739   EVT SrcVT = N0.getValueType();
46740 
46741   SDValue BC0 =
46742       N->isOnlyUserOf(N0.getNode()) ? peekThroughOneUseBitcasts(N0) : N0;
46743   SDValue BC1 =
46744       N->isOnlyUserOf(N1.getNode()) ? peekThroughOneUseBitcasts(N1) : N1;
46745 
46746   // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
46747   // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
46748   // truncation trees that help us avoid lane crossing shuffles.
46749   // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
46750   // TODO: We don't handle vXf64 shuffles yet.
46751   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
46752     if (SDValue BCSrc = getSplitVectorSrc(BC0, BC1, false)) {
46753       SmallVector<SDValue> ShuffleOps;
46754       SmallVector<int> ShuffleMask, ScaledMask;
46755       SDValue Vec = peekThroughBitcasts(BCSrc);
46756       if (getTargetShuffleInputs(Vec, ShuffleOps, ShuffleMask, DAG)) {
46757         resolveTargetShuffleInputsAndMask(ShuffleOps, ShuffleMask);
46758         // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
46759         // shuffle to a v4X64 width - we can probably relax this in the future.
46760         if (!isAnyZero(ShuffleMask) && ShuffleOps.size() == 1 &&
46761             ShuffleOps[0].getValueType().is256BitVector() &&
46762             scaleShuffleElements(ShuffleMask, 4, ScaledMask)) {
46763           SDValue Lo, Hi;
46764           MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
46765           std::tie(Lo, Hi) = DAG.SplitVector(ShuffleOps[0], DL);
46766           Lo = DAG.getBitcast(SrcVT, Lo);
46767           Hi = DAG.getBitcast(SrcVT, Hi);
46768           SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
46769           Res = DAG.getBitcast(ShufVT, Res);
46770           Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ScaledMask);
46771           return DAG.getBitcast(VT, Res);
46772         }
46773       }
46774     }
46775   }
46776 
46777   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(Z,W)) -> SHUFFLE(HOP()).
46778   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
46779     // If either/both ops are a shuffle that can scale to v2x64,
46780     // then see if we can perform this as a v4x32 post shuffle.
46781     SmallVector<SDValue> Ops0, Ops1;
46782     SmallVector<int> Mask0, Mask1, ScaledMask0, ScaledMask1;
46783     bool IsShuf0 =
46784         getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
46785         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
46786         all_of(Ops0, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
46787     bool IsShuf1 =
46788         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
46789         scaleShuffleElements(Mask1, 2, ScaledMask1) &&
46790         all_of(Ops1, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
46791     if (IsShuf0 || IsShuf1) {
46792       if (!IsShuf0) {
46793         Ops0.assign({BC0});
46794         ScaledMask0.assign({0, 1});
46795       }
46796       if (!IsShuf1) {
46797         Ops1.assign({BC1});
46798         ScaledMask1.assign({0, 1});
46799       }
46800 
46801       SDValue LHS, RHS;
46802       int PostShuffle[4] = {-1, -1, -1, -1};
46803       auto FindShuffleOpAndIdx = [&](int M, int &Idx, ArrayRef<SDValue> Ops) {
46804         if (M < 0)
46805           return true;
46806         Idx = M % 2;
46807         SDValue Src = Ops[M / 2];
46808         if (!LHS || LHS == Src) {
46809           LHS = Src;
46810           return true;
46811         }
46812         if (!RHS || RHS == Src) {
46813           Idx += 2;
46814           RHS = Src;
46815           return true;
46816         }
46817         return false;
46818       };
46819       if (FindShuffleOpAndIdx(ScaledMask0[0], PostShuffle[0], Ops0) &&
46820           FindShuffleOpAndIdx(ScaledMask0[1], PostShuffle[1], Ops0) &&
46821           FindShuffleOpAndIdx(ScaledMask1[0], PostShuffle[2], Ops1) &&
46822           FindShuffleOpAndIdx(ScaledMask1[1], PostShuffle[3], Ops1)) {
46823         LHS = DAG.getBitcast(SrcVT, LHS);
46824         RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
46825         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
46826         SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
46827         Res = DAG.getBitcast(ShufVT, Res);
46828         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
46829         return DAG.getBitcast(VT, Res);
46830       }
46831     }
46832   }
46833 
46834   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
46835   if (VT.is256BitVector() && Subtarget.hasInt256()) {
46836     SmallVector<int> Mask0, Mask1;
46837     SmallVector<SDValue> Ops0, Ops1;
46838     SmallVector<int, 2> ScaledMask0, ScaledMask1;
46839     if (getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
46840         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
46841         !Ops0.empty() && !Ops1.empty() &&
46842         all_of(Ops0,
46843                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
46844         all_of(Ops1,
46845                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
46846         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
46847         scaleShuffleElements(Mask1, 2, ScaledMask1)) {
46848       SDValue Op00 = peekThroughBitcasts(Ops0.front());
46849       SDValue Op10 = peekThroughBitcasts(Ops1.front());
46850       SDValue Op01 = peekThroughBitcasts(Ops0.back());
46851       SDValue Op11 = peekThroughBitcasts(Ops1.back());
46852       if ((Op00 == Op11) && (Op01 == Op10)) {
46853         std::swap(Op10, Op11);
46854         ShuffleVectorSDNode::commuteMask(ScaledMask1);
46855       }
46856       if ((Op00 == Op10) && (Op01 == Op11)) {
46857         const int Map[4] = {0, 2, 1, 3};
46858         SmallVector<int, 4> ShuffleMask(
46859             {Map[ScaledMask0[0]], Map[ScaledMask1[0]], Map[ScaledMask0[1]],
46860              Map[ScaledMask1[1]]});
46861         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
46862         SDValue Res = DAG.getNode(Opcode, DL, VT, DAG.getBitcast(SrcVT, Op00),
46863                                   DAG.getBitcast(SrcVT, Op01));
46864         Res = DAG.getBitcast(ShufVT, Res);
46865         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
46866         return DAG.getBitcast(VT, Res);
46867       }
46868     }
46869   }
46870 
46871   return SDValue();
46872 }
46873 
46874 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
46875                                  TargetLowering::DAGCombinerInfo &DCI,
46876                                  const X86Subtarget &Subtarget) {
46877   unsigned Opcode = N->getOpcode();
46878   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
46879          "Unexpected pack opcode");
46880 
46881   EVT VT = N->getValueType(0);
46882   SDValue N0 = N->getOperand(0);
46883   SDValue N1 = N->getOperand(1);
46884   unsigned NumDstElts = VT.getVectorNumElements();
46885   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
46886   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
46887   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
46888          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
46889          "Unexpected PACKSS/PACKUS input type");
46890 
46891   bool IsSigned = (X86ISD::PACKSS == Opcode);
46892 
46893   // Constant Folding.
46894   APInt UndefElts0, UndefElts1;
46895   SmallVector<APInt, 32> EltBits0, EltBits1;
46896   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
46897       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
46898       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
46899       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
46900     unsigned NumLanes = VT.getSizeInBits() / 128;
46901     unsigned NumSrcElts = NumDstElts / 2;
46902     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
46903     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
46904 
46905     APInt Undefs(NumDstElts, 0);
46906     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getZero(DstBitsPerElt));
46907     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
46908       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
46909         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
46910         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
46911         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
46912 
46913         if (UndefElts[SrcIdx]) {
46914           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
46915           continue;
46916         }
46917 
46918         APInt &Val = EltBits[SrcIdx];
46919         if (IsSigned) {
46920           // PACKSS: Truncate signed value with signed saturation.
46921           // Source values less than dst minint are saturated to minint.
46922           // Source values greater than dst maxint are saturated to maxint.
46923           if (Val.isSignedIntN(DstBitsPerElt))
46924             Val = Val.trunc(DstBitsPerElt);
46925           else if (Val.isNegative())
46926             Val = APInt::getSignedMinValue(DstBitsPerElt);
46927           else
46928             Val = APInt::getSignedMaxValue(DstBitsPerElt);
46929         } else {
46930           // PACKUS: Truncate signed value with unsigned saturation.
46931           // Source values less than zero are saturated to zero.
46932           // Source values greater than dst maxuint are saturated to maxuint.
46933           if (Val.isIntN(DstBitsPerElt))
46934             Val = Val.trunc(DstBitsPerElt);
46935           else if (Val.isNegative())
46936             Val = APInt::getZero(DstBitsPerElt);
46937           else
46938             Val = APInt::getAllOnes(DstBitsPerElt);
46939         }
46940         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
46941       }
46942     }
46943 
46944     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
46945   }
46946 
46947   // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
46948   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
46949     return V;
46950 
46951   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
46952   // truncate to create a larger truncate.
46953   if (Subtarget.hasAVX512() &&
46954       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
46955       N0.getOperand(0).getValueType() == MVT::v8i32) {
46956     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
46957         (!IsSigned &&
46958          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
46959       if (Subtarget.hasVLX())
46960         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
46961 
46962       // Widen input to v16i32 so we can truncate that.
46963       SDLoc dl(N);
46964       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
46965                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
46966       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
46967     }
46968   }
46969 
46970   // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
46971   if (VT.is128BitVector()) {
46972     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
46973     SDValue Src0, Src1;
46974     if (N0.getOpcode() == ExtOpc &&
46975         N0.getOperand(0).getValueType().is64BitVector() &&
46976         N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
46977       Src0 = N0.getOperand(0);
46978     }
46979     if (N1.getOpcode() == ExtOpc &&
46980         N1.getOperand(0).getValueType().is64BitVector() &&
46981         N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
46982       Src1 = N1.getOperand(0);
46983     }
46984     if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
46985       assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)");
46986       Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
46987       Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
46988       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
46989     }
46990 
46991     // Try again with pack(*_extend_vector_inreg, undef).
46992     unsigned VecInRegOpc = IsSigned ? ISD::SIGN_EXTEND_VECTOR_INREG
46993                                     : ISD::ZERO_EXTEND_VECTOR_INREG;
46994     if (N0.getOpcode() == VecInRegOpc && N1.isUndef() &&
46995         N0.getOperand(0).getScalarValueSizeInBits() < DstBitsPerElt)
46996       return getEXTEND_VECTOR_INREG(ExtOpc, SDLoc(N), VT, N0.getOperand(0),
46997                                     DAG);
46998   }
46999 
47000   // Attempt to combine as shuffle.
47001   SDValue Op(N, 0);
47002   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47003     return Res;
47004 
47005   return SDValue();
47006 }
47007 
47008 static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
47009                                     TargetLowering::DAGCombinerInfo &DCI,
47010                                     const X86Subtarget &Subtarget) {
47011   assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||
47012           X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
47013          "Unexpected horizontal add/sub opcode");
47014 
47015   if (!shouldUseHorizontalOp(true, DAG, Subtarget)) {
47016     MVT VT = N->getSimpleValueType(0);
47017     SDValue LHS = N->getOperand(0);
47018     SDValue RHS = N->getOperand(1);
47019 
47020     // HOP(HOP'(X,X),HOP'(Y,Y)) -> HOP(PERMUTE(HOP'(X,Y)),PERMUTE(HOP'(X,Y)).
47021     if (LHS != RHS && LHS.getOpcode() == N->getOpcode() &&
47022         LHS.getOpcode() == RHS.getOpcode() &&
47023         LHS.getValueType() == RHS.getValueType() &&
47024         N->isOnlyUserOf(LHS.getNode()) && N->isOnlyUserOf(RHS.getNode())) {
47025       SDValue LHS0 = LHS.getOperand(0);
47026       SDValue LHS1 = LHS.getOperand(1);
47027       SDValue RHS0 = RHS.getOperand(0);
47028       SDValue RHS1 = RHS.getOperand(1);
47029       if ((LHS0 == LHS1 || LHS0.isUndef() || LHS1.isUndef()) &&
47030           (RHS0 == RHS1 || RHS0.isUndef() || RHS1.isUndef())) {
47031         SDLoc DL(N);
47032         SDValue Res = DAG.getNode(LHS.getOpcode(), DL, LHS.getValueType(),
47033                                   LHS0.isUndef() ? LHS1 : LHS0,
47034                                   RHS0.isUndef() ? RHS1 : RHS0);
47035         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
47036         Res = DAG.getBitcast(ShufVT, Res);
47037         SDValue NewLHS =
47038             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
47039                         getV4X86ShuffleImm8ForMask({0, 1, 0, 1}, DL, DAG));
47040         SDValue NewRHS =
47041             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
47042                         getV4X86ShuffleImm8ForMask({2, 3, 2, 3}, DL, DAG));
47043         return DAG.getNode(N->getOpcode(), DL, VT, DAG.getBitcast(VT, NewLHS),
47044                            DAG.getBitcast(VT, NewRHS));
47045       }
47046     }
47047   }
47048 
47049   // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
47050   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
47051     return V;
47052 
47053   return SDValue();
47054 }
47055 
47056 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
47057                                      TargetLowering::DAGCombinerInfo &DCI,
47058                                      const X86Subtarget &Subtarget) {
47059   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
47060           X86ISD::VSRL == N->getOpcode()) &&
47061          "Unexpected shift opcode");
47062   EVT VT = N->getValueType(0);
47063   SDValue N0 = N->getOperand(0);
47064   SDValue N1 = N->getOperand(1);
47065 
47066   // Shift zero -> zero.
47067   if (ISD::isBuildVectorAllZeros(N0.getNode()))
47068     return DAG.getConstant(0, SDLoc(N), VT);
47069 
47070   // Detect constant shift amounts.
47071   APInt UndefElts;
47072   SmallVector<APInt, 32> EltBits;
47073   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
47074     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
47075     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
47076                                       EltBits[0].getZExtValue(), DAG);
47077   }
47078 
47079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47080   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
47081   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
47082     return SDValue(N, 0);
47083 
47084   return SDValue();
47085 }
47086 
47087 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
47088                                      TargetLowering::DAGCombinerInfo &DCI,
47089                                      const X86Subtarget &Subtarget) {
47090   unsigned Opcode = N->getOpcode();
47091   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
47092           X86ISD::VSRLI == Opcode) &&
47093          "Unexpected shift opcode");
47094   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
47095   EVT VT = N->getValueType(0);
47096   SDValue N0 = N->getOperand(0);
47097   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
47098   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
47099          "Unexpected value type");
47100   assert(N->getOperand(1).getValueType() == MVT::i8 &&
47101          "Unexpected shift amount type");
47102 
47103   // (shift undef, X) -> 0
47104   if (N0.isUndef())
47105     return DAG.getConstant(0, SDLoc(N), VT);
47106 
47107   // Out of range logical bit shifts are guaranteed to be zero.
47108   // Out of range arithmetic bit shifts splat the sign bit.
47109   unsigned ShiftVal = N->getConstantOperandVal(1);
47110   if (ShiftVal >= NumBitsPerElt) {
47111     if (LogicalShift)
47112       return DAG.getConstant(0, SDLoc(N), VT);
47113     ShiftVal = NumBitsPerElt - 1;
47114   }
47115 
47116   // (shift X, 0) -> X
47117   if (!ShiftVal)
47118     return N0;
47119 
47120   // (shift 0, C) -> 0
47121   if (ISD::isBuildVectorAllZeros(N0.getNode()))
47122     // N0 is all zeros or undef. We guarantee that the bits shifted into the
47123     // result are all zeros, not undef.
47124     return DAG.getConstant(0, SDLoc(N), VT);
47125 
47126   // (VSRAI -1, C) -> -1
47127   if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
47128     // N0 is all ones or undef. We guarantee that the bits shifted into the
47129     // result are all ones, not undef.
47130     return DAG.getConstant(-1, SDLoc(N), VT);
47131 
47132   // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
47133   if (Opcode == N0.getOpcode()) {
47134     unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
47135     unsigned NewShiftVal = ShiftVal + ShiftVal2;
47136     if (NewShiftVal >= NumBitsPerElt) {
47137       // Out of range logical bit shifts are guaranteed to be zero.
47138       // Out of range arithmetic bit shifts splat the sign bit.
47139       if (LogicalShift)
47140         return DAG.getConstant(0, SDLoc(N), VT);
47141       NewShiftVal = NumBitsPerElt - 1;
47142     }
47143     return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
47144                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
47145   }
47146 
47147   // We can decode 'whole byte' logical bit shifts as shuffles.
47148   if (LogicalShift && (ShiftVal % 8) == 0) {
47149     SDValue Op(N, 0);
47150     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47151       return Res;
47152   }
47153 
47154   // Constant Folding.
47155   APInt UndefElts;
47156   SmallVector<APInt, 32> EltBits;
47157   if (N->isOnlyUserOf(N0.getNode()) &&
47158       getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
47159     assert(EltBits.size() == VT.getVectorNumElements() &&
47160            "Unexpected shift value type");
47161     // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
47162     // created an undef input due to no input bits being demanded, but user
47163     // still expects 0 in other bits.
47164     for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
47165       APInt &Elt = EltBits[i];
47166       if (UndefElts[i])
47167         Elt = 0;
47168       else if (X86ISD::VSHLI == Opcode)
47169         Elt <<= ShiftVal;
47170       else if (X86ISD::VSRAI == Opcode)
47171         Elt.ashrInPlace(ShiftVal);
47172       else
47173         Elt.lshrInPlace(ShiftVal);
47174     }
47175     // Reset undef elements since they were zeroed above.
47176     UndefElts = 0;
47177     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
47178   }
47179 
47180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47181   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBitsPerElt),
47182                                DCI))
47183     return SDValue(N, 0);
47184 
47185   return SDValue();
47186 }
47187 
47188 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
47189                                    TargetLowering::DAGCombinerInfo &DCI,
47190                                    const X86Subtarget &Subtarget) {
47191   EVT VT = N->getValueType(0);
47192   assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||
47193           (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) ||
47194           N->getOpcode() == ISD::INSERT_VECTOR_ELT) &&
47195          "Unexpected vector insertion");
47196 
47197   if (N->getOpcode() == X86ISD::PINSRB || N->getOpcode() == X86ISD::PINSRW) {
47198     unsigned NumBitsPerElt = VT.getScalarSizeInBits();
47199     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47200     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
47201                                  APInt::getAllOnes(NumBitsPerElt), DCI))
47202       return SDValue(N, 0);
47203   }
47204 
47205   // Attempt to combine insertion patterns to a shuffle.
47206   if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
47207     SDValue Op(N, 0);
47208     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47209       return Res;
47210   }
47211 
47212   return SDValue();
47213 }
47214 
47215 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
47216 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
47217 /// OR -> CMPNEQSS.
47218 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
47219                                    TargetLowering::DAGCombinerInfo &DCI,
47220                                    const X86Subtarget &Subtarget) {
47221   unsigned opcode;
47222 
47223   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
47224   // we're requiring SSE2 for both.
47225   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
47226     SDValue N0 = N->getOperand(0);
47227     SDValue N1 = N->getOperand(1);
47228     SDValue CMP0 = N0.getOperand(1);
47229     SDValue CMP1 = N1.getOperand(1);
47230     SDLoc DL(N);
47231 
47232     // The SETCCs should both refer to the same CMP.
47233     if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
47234       return SDValue();
47235 
47236     SDValue CMP00 = CMP0->getOperand(0);
47237     SDValue CMP01 = CMP0->getOperand(1);
47238     EVT     VT    = CMP00.getValueType();
47239 
47240     if (VT == MVT::f32 || VT == MVT::f64 ||
47241         (VT == MVT::f16 && Subtarget.hasFP16())) {
47242       bool ExpectingFlags = false;
47243       // Check for any users that want flags:
47244       for (const SDNode *U : N->uses()) {
47245         if (ExpectingFlags)
47246           break;
47247 
47248         switch (U->getOpcode()) {
47249         default:
47250         case ISD::BR_CC:
47251         case ISD::BRCOND:
47252         case ISD::SELECT:
47253           ExpectingFlags = true;
47254           break;
47255         case ISD::CopyToReg:
47256         case ISD::SIGN_EXTEND:
47257         case ISD::ZERO_EXTEND:
47258         case ISD::ANY_EXTEND:
47259           break;
47260         }
47261       }
47262 
47263       if (!ExpectingFlags) {
47264         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
47265         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
47266 
47267         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
47268           X86::CondCode tmp = cc0;
47269           cc0 = cc1;
47270           cc1 = tmp;
47271         }
47272 
47273         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
47274             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
47275           // FIXME: need symbolic constants for these magic numbers.
47276           // See X86ATTInstPrinter.cpp:printSSECC().
47277           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
47278           if (Subtarget.hasAVX512()) {
47279             SDValue FSetCC =
47280                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
47281                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
47282             // Need to fill with zeros to ensure the bitcast will produce zeroes
47283             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
47284             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
47285                                       DAG.getConstant(0, DL, MVT::v16i1),
47286                                       FSetCC, DAG.getIntPtrConstant(0, DL));
47287             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
47288                                       N->getSimpleValueType(0));
47289           }
47290           SDValue OnesOrZeroesF =
47291               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
47292                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
47293 
47294           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
47295           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
47296 
47297           if (is64BitFP && !Subtarget.is64Bit()) {
47298             // On a 32-bit target, we cannot bitcast the 64-bit float to a
47299             // 64-bit integer, since that's not a legal type. Since
47300             // OnesOrZeroesF is all ones or all zeroes, we don't need all the
47301             // bits, but can do this little dance to extract the lowest 32 bits
47302             // and work with those going forward.
47303             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
47304                                            OnesOrZeroesF);
47305             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
47306             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
47307                                         Vector32, DAG.getIntPtrConstant(0, DL));
47308             IntVT = MVT::i32;
47309           }
47310 
47311           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
47312           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
47313                                       DAG.getConstant(1, DL, IntVT));
47314           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
47315                                               ANDed);
47316           return OneBitOfTruth;
47317         }
47318       }
47319     }
47320   }
47321   return SDValue();
47322 }
47323 
47324 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
47325 static SDValue combineAndNotIntoANDNP(SDNode *N, SelectionDAG &DAG) {
47326   assert(N->getOpcode() == ISD::AND);
47327 
47328   MVT VT = N->getSimpleValueType(0);
47329   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
47330     return SDValue();
47331 
47332   SDValue X, Y;
47333   SDValue N0 = N->getOperand(0);
47334   SDValue N1 = N->getOperand(1);
47335 
47336   auto GetNot = [&VT, &DAG](SDValue V) {
47337     // Basic X = NOT(Y) detection.
47338     if (SDValue Not = IsNOT(V, DAG))
47339       return Not;
47340     // Fold BROADCAST(NOT(Y)) -> BROADCAST(Y).
47341     if (V.getOpcode() == X86ISD::VBROADCAST) {
47342       SDValue Src = V.getOperand(0);
47343       EVT SrcVT = Src.getValueType();
47344       if (!SrcVT.isVector())
47345         return SDValue();
47346       if (SDValue Not = IsNOT(Src, DAG))
47347         return DAG.getNode(X86ISD::VBROADCAST, SDLoc(V), VT,
47348                            DAG.getBitcast(SrcVT, Not));
47349     }
47350     return SDValue();
47351   };
47352 
47353   if (SDValue Not = GetNot(N0)) {
47354     X = Not;
47355     Y = N1;
47356   } else if (SDValue Not = GetNot(N1)) {
47357     X = Not;
47358     Y = N0;
47359   } else
47360     return SDValue();
47361 
47362   X = DAG.getBitcast(VT, X);
47363   Y = DAG.getBitcast(VT, Y);
47364   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
47365 }
47366 
47367 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
47368 // logical operations, like in the example below.
47369 //   or (and (truncate x, truncate y)),
47370 //      (xor (truncate z, build_vector (constants)))
47371 // Given a target type \p VT, we generate
47372 //   or (and x, y), (xor z, zext(build_vector (constants)))
47373 // given x, y and z are of type \p VT. We can do so, if operands are either
47374 // truncates from VT types, the second operand is a vector of constants or can
47375 // be recursively promoted.
47376 static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
47377                                      unsigned Depth) {
47378   // Limit recursion to avoid excessive compile times.
47379   if (Depth >= SelectionDAG::MaxRecursionDepth)
47380     return SDValue();
47381 
47382   if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
47383       N->getOpcode() != ISD::OR)
47384     return SDValue();
47385 
47386   SDValue N0 = N->getOperand(0);
47387   SDValue N1 = N->getOperand(1);
47388   SDLoc DL(N);
47389 
47390   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47391   if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
47392     return SDValue();
47393 
47394   if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
47395     N0 = NN0;
47396   else {
47397     // The Left side has to be a trunc.
47398     if (N0.getOpcode() != ISD::TRUNCATE)
47399       return SDValue();
47400 
47401     // The type of the truncated inputs.
47402     if (N0.getOperand(0).getValueType() != VT)
47403       return SDValue();
47404 
47405     N0 = N0.getOperand(0);
47406   }
47407 
47408   if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
47409     N1 = NN1;
47410   else {
47411     // The right side has to be a 'trunc' or a constant vector.
47412     bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
47413                     N1.getOperand(0).getValueType() == VT;
47414     if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
47415       return SDValue();
47416 
47417     if (RHSTrunc)
47418       N1 = N1.getOperand(0);
47419     else
47420       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
47421   }
47422 
47423   return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
47424 }
47425 
47426 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
47427 // register. In most cases we actually compare or select YMM-sized registers
47428 // and mixing the two types creates horrible code. This method optimizes
47429 // some of the transition sequences.
47430 // Even with AVX-512 this is still useful for removing casts around logical
47431 // operations on vXi1 mask types.
47432 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
47433                                      const X86Subtarget &Subtarget) {
47434   EVT VT = N->getValueType(0);
47435   assert(VT.isVector() && "Expected vector type");
47436 
47437   SDLoc DL(N);
47438   assert((N->getOpcode() == ISD::ANY_EXTEND ||
47439           N->getOpcode() == ISD::ZERO_EXTEND ||
47440           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
47441 
47442   SDValue Narrow = N->getOperand(0);
47443   EVT NarrowVT = Narrow.getValueType();
47444 
47445   // Generate the wide operation.
47446   SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
47447   if (!Op)
47448     return SDValue();
47449   switch (N->getOpcode()) {
47450   default: llvm_unreachable("Unexpected opcode");
47451   case ISD::ANY_EXTEND:
47452     return Op;
47453   case ISD::ZERO_EXTEND:
47454     return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
47455   case ISD::SIGN_EXTEND:
47456     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
47457                        Op, DAG.getValueType(NarrowVT));
47458   }
47459 }
47460 
47461 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
47462   unsigned FPOpcode;
47463   switch (Opcode) {
47464   default: llvm_unreachable("Unexpected input node for FP logic conversion");
47465   case ISD::AND: FPOpcode = X86ISD::FAND; break;
47466   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
47467   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
47468   }
47469   return FPOpcode;
47470 }
47471 
47472 /// If both input operands of a logic op are being cast from floating-point
47473 /// types or FP compares, try to convert this into a floating-point logic node
47474 /// to avoid unnecessary moves from SSE to integer registers.
47475 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
47476                                         TargetLowering::DAGCombinerInfo &DCI,
47477                                         const X86Subtarget &Subtarget) {
47478   EVT VT = N->getValueType(0);
47479   SDValue N0 = N->getOperand(0);
47480   SDValue N1 = N->getOperand(1);
47481   SDLoc DL(N);
47482 
47483   if (!((N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) ||
47484         (N0.getOpcode() == ISD::SETCC && N1.getOpcode() == ISD::SETCC)))
47485     return SDValue();
47486 
47487   SDValue N00 = N0.getOperand(0);
47488   SDValue N10 = N1.getOperand(0);
47489   EVT N00Type = N00.getValueType();
47490   EVT N10Type = N10.getValueType();
47491 
47492   // Ensure that both types are the same and are legal scalar fp types.
47493   if (N00Type != N10Type || !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
47494                               (Subtarget.hasSSE2() && N00Type == MVT::f64) ||
47495                               (Subtarget.hasFP16() && N00Type == MVT::f16)))
47496     return SDValue();
47497 
47498   if (N0.getOpcode() == ISD::BITCAST && !DCI.isBeforeLegalizeOps()) {
47499     unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
47500     SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
47501     return DAG.getBitcast(VT, FPLogic);
47502   }
47503 
47504   if (VT != MVT::i1 || N0.getOpcode() != ISD::SETCC || !N0.hasOneUse() ||
47505       !N1.hasOneUse())
47506     return SDValue();
47507 
47508   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0.getOperand(2))->get();
47509   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
47510 
47511   // The vector ISA for FP predicates is incomplete before AVX, so converting
47512   // COMIS* to CMPS* may not be a win before AVX.
47513   if (!Subtarget.hasAVX() &&
47514       !(cheapX86FSETCC_SSE(CC0) && cheapX86FSETCC_SSE(CC1)))
47515     return SDValue();
47516 
47517   // Convert scalar FP compares and logic to vector compares (COMIS* to CMPS*)
47518   // and vector logic:
47519   // logic (setcc N00, N01), (setcc N10, N11) -->
47520   // extelt (logic (setcc (s2v N00), (s2v N01)), setcc (s2v N10), (s2v N11))), 0
47521   unsigned NumElts = 128 / N00Type.getSizeInBits();
47522   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), N00Type, NumElts);
47523   EVT BoolVecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
47524   SDValue ZeroIndex = DAG.getVectorIdxConstant(0, DL);
47525   SDValue N01 = N0.getOperand(1);
47526   SDValue N11 = N1.getOperand(1);
47527   SDValue Vec00 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N00);
47528   SDValue Vec01 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N01);
47529   SDValue Vec10 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N10);
47530   SDValue Vec11 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N11);
47531   SDValue Setcc0 = DAG.getSetCC(DL, BoolVecVT, Vec00, Vec01, CC0);
47532   SDValue Setcc1 = DAG.getSetCC(DL, BoolVecVT, Vec10, Vec11, CC1);
47533   SDValue Logic = DAG.getNode(N->getOpcode(), DL, BoolVecVT, Setcc0, Setcc1);
47534   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Logic, ZeroIndex);
47535 }
47536 
47537 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
47538 // to reduce XMM->GPR traffic.
47539 static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
47540   unsigned Opc = N->getOpcode();
47541   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
47542          "Unexpected bit opcode");
47543 
47544   SDValue N0 = N->getOperand(0);
47545   SDValue N1 = N->getOperand(1);
47546 
47547   // Both operands must be single use MOVMSK.
47548   if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
47549       N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
47550     return SDValue();
47551 
47552   SDValue Vec0 = N0.getOperand(0);
47553   SDValue Vec1 = N1.getOperand(0);
47554   EVT VecVT0 = Vec0.getValueType();
47555   EVT VecVT1 = Vec1.getValueType();
47556 
47557   // Both MOVMSK operands must be from vectors of the same size and same element
47558   // size, but its OK for a fp/int diff.
47559   if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
47560       VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
47561     return SDValue();
47562 
47563   SDLoc DL(N);
47564   unsigned VecOpc =
47565       VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
47566   SDValue Result =
47567       DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
47568   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
47569 }
47570 
47571 // Attempt to fold BITOP(SHIFT(X,Z),SHIFT(Y,Z)) -> SHIFT(BITOP(X,Y),Z).
47572 // NOTE: This is a very limited case of what SimplifyUsingDistributiveLaws
47573 // handles in InstCombine.
47574 static SDValue combineBitOpWithShift(SDNode *N, SelectionDAG &DAG) {
47575   unsigned Opc = N->getOpcode();
47576   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
47577          "Unexpected bit opcode");
47578 
47579   SDValue N0 = N->getOperand(0);
47580   SDValue N1 = N->getOperand(1);
47581   EVT VT = N->getValueType(0);
47582 
47583   // Both operands must be single use.
47584   if (!N0.hasOneUse() || !N1.hasOneUse())
47585     return SDValue();
47586 
47587   // Search for matching shifts.
47588   SDValue BC0 = peekThroughOneUseBitcasts(N0);
47589   SDValue BC1 = peekThroughOneUseBitcasts(N1);
47590 
47591   unsigned BCOpc = BC0.getOpcode();
47592   EVT BCVT = BC0.getValueType();
47593   if (BCOpc != BC1->getOpcode() || BCVT != BC1.getValueType())
47594     return SDValue();
47595 
47596   switch (BCOpc) {
47597   case X86ISD::VSHLI:
47598   case X86ISD::VSRLI:
47599   case X86ISD::VSRAI: {
47600     if (BC0.getOperand(1) != BC1.getOperand(1))
47601       return SDValue();
47602 
47603     SDLoc DL(N);
47604     SDValue BitOp =
47605         DAG.getNode(Opc, DL, BCVT, BC0.getOperand(0), BC1.getOperand(0));
47606     SDValue Shift = DAG.getNode(BCOpc, DL, BCVT, BitOp, BC0.getOperand(1));
47607     return DAG.getBitcast(VT, Shift);
47608   }
47609   }
47610 
47611   return SDValue();
47612 }
47613 
47614 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
47615 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
47616 /// with a shift-right to eliminate loading the vector constant mask value.
47617 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
47618                                      const X86Subtarget &Subtarget) {
47619   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
47620   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
47621   EVT VT = Op0.getValueType();
47622   if (VT != Op1.getValueType() || !VT.isSimple() || !VT.isInteger())
47623     return SDValue();
47624 
47625   // Try to convert an "is positive" signbit masking operation into arithmetic
47626   // shift and "andn". This saves a materialization of a -1 vector constant.
47627   // The "is negative" variant should be handled more generally because it only
47628   // requires "and" rather than "andn":
47629   // and (pcmpgt X, -1), Y --> pandn (vsrai X, BitWidth - 1), Y
47630   //
47631   // This is limited to the original type to avoid producing even more bitcasts.
47632   // If the bitcasts can't be eliminated, then it is unlikely that this fold
47633   // will be profitable.
47634   if (N->getValueType(0) == VT &&
47635       supportedVectorShiftWithImm(VT.getSimpleVT(), Subtarget, ISD::SRA)) {
47636     SDValue X, Y;
47637     if (Op1.hasOneUse() && Op1.getOpcode() == X86ISD::PCMPGT &&
47638         isAllOnesOrAllOnesSplat(Op1.getOperand(1))) {
47639       X = Op1.getOperand(0);
47640       Y = Op0;
47641     } else if (Op0.hasOneUse() && Op0.getOpcode() == X86ISD::PCMPGT &&
47642                isAllOnesOrAllOnesSplat(Op0.getOperand(1))) {
47643       X = Op0.getOperand(0);
47644       Y = Op1;
47645     }
47646     if (X && Y) {
47647       SDLoc DL(N);
47648       SDValue Sra =
47649           getTargetVShiftByConstNode(X86ISD::VSRAI, DL, VT.getSimpleVT(), X,
47650                                      VT.getScalarSizeInBits() - 1, DAG);
47651       return DAG.getNode(X86ISD::ANDNP, DL, VT, Sra, Y);
47652     }
47653   }
47654 
47655   APInt SplatVal;
47656   if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
47657       !SplatVal.isMask())
47658     return SDValue();
47659 
47660   // Don't prevent creation of ANDN.
47661   if (isBitwiseNot(Op0))
47662     return SDValue();
47663 
47664   if (!supportedVectorShiftWithImm(VT.getSimpleVT(), Subtarget, ISD::SRL))
47665     return SDValue();
47666 
47667   unsigned EltBitWidth = VT.getScalarSizeInBits();
47668   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
47669     return SDValue();
47670 
47671   SDLoc DL(N);
47672   unsigned ShiftVal = SplatVal.countTrailingOnes();
47673   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
47674   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT, Op0, ShAmt);
47675   return DAG.getBitcast(N->getValueType(0), Shift);
47676 }
47677 
47678 // Get the index node from the lowered DAG of a GEP IR instruction with one
47679 // indexing dimension.
47680 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
47681   if (Ld->isIndexed())
47682     return SDValue();
47683 
47684   SDValue Base = Ld->getBasePtr();
47685 
47686   if (Base.getOpcode() != ISD::ADD)
47687     return SDValue();
47688 
47689   SDValue ShiftedIndex = Base.getOperand(0);
47690 
47691   if (ShiftedIndex.getOpcode() != ISD::SHL)
47692     return SDValue();
47693 
47694   return ShiftedIndex.getOperand(0);
47695 
47696 }
47697 
47698 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
47699   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
47700     switch (VT.getSizeInBits()) {
47701     default: return false;
47702     case 64: return Subtarget.is64Bit() ? true : false;
47703     case 32: return true;
47704     }
47705   }
47706   return false;
47707 }
47708 
47709 // This function recognizes cases where X86 bzhi instruction can replace and
47710 // 'and-load' sequence.
47711 // In case of loading integer value from an array of constants which is defined
47712 // as follows:
47713 //
47714 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
47715 //
47716 // then applying a bitwise and on the result with another input.
47717 // It's equivalent to performing bzhi (zero high bits) on the input, with the
47718 // same index of the load.
47719 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
47720                                     const X86Subtarget &Subtarget) {
47721   MVT VT = Node->getSimpleValueType(0);
47722   SDLoc dl(Node);
47723 
47724   // Check if subtarget has BZHI instruction for the node's type
47725   if (!hasBZHI(Subtarget, VT))
47726     return SDValue();
47727 
47728   // Try matching the pattern for both operands.
47729   for (unsigned i = 0; i < 2; i++) {
47730     SDValue N = Node->getOperand(i);
47731     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
47732 
47733      // continue if the operand is not a load instruction
47734     if (!Ld)
47735       return SDValue();
47736 
47737     const Value *MemOp = Ld->getMemOperand()->getValue();
47738 
47739     if (!MemOp)
47740       return SDValue();
47741 
47742     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
47743       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
47744         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
47745 
47746           Constant *Init = GV->getInitializer();
47747           Type *Ty = Init->getType();
47748           if (!isa<ConstantDataArray>(Init) ||
47749               !Ty->getArrayElementType()->isIntegerTy() ||
47750               Ty->getArrayElementType()->getScalarSizeInBits() !=
47751                   VT.getSizeInBits() ||
47752               Ty->getArrayNumElements() >
47753                   Ty->getArrayElementType()->getScalarSizeInBits())
47754             continue;
47755 
47756           // Check if the array's constant elements are suitable to our case.
47757           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
47758           bool ConstantsMatch = true;
47759           for (uint64_t j = 0; j < ArrayElementCount; j++) {
47760             auto *Elem = cast<ConstantInt>(Init->getAggregateElement(j));
47761             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
47762               ConstantsMatch = false;
47763               break;
47764             }
47765           }
47766           if (!ConstantsMatch)
47767             continue;
47768 
47769           // Do the transformation (For 32-bit type):
47770           // -> (and (load arr[idx]), inp)
47771           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
47772           //    that will be replaced with one bzhi instruction.
47773           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
47774           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
47775 
47776           // Get the Node which indexes into the array.
47777           SDValue Index = getIndexFromUnindexedLoad(Ld);
47778           if (!Index)
47779             return SDValue();
47780           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
47781 
47782           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
47783           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
47784 
47785           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
47786           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
47787 
47788           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
47789         }
47790       }
47791     }
47792   }
47793   return SDValue();
47794 }
47795 
47796 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
47797 // Where C is a mask containing the same number of bits as the setcc and
47798 // where the setcc will freely 0 upper bits of k-register. We can replace the
47799 // undef in the concat with 0s and remove the AND. This mainly helps with
47800 // v2i1/v4i1 setcc being casted to scalar.
47801 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
47802                                              const X86Subtarget &Subtarget) {
47803   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
47804 
47805   EVT VT = N->getValueType(0);
47806 
47807   // Make sure this is an AND with constant. We will check the value of the
47808   // constant later.
47809   if (!isa<ConstantSDNode>(N->getOperand(1)))
47810     return SDValue();
47811 
47812   // This is implied by the ConstantSDNode.
47813   assert(!VT.isVector() && "Expected scalar VT!");
47814 
47815   if (N->getOperand(0).getOpcode() != ISD::BITCAST ||
47816       !N->getOperand(0).hasOneUse() ||
47817       !N->getOperand(0).getOperand(0).hasOneUse())
47818     return SDValue();
47819 
47820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47821   SDValue Src = N->getOperand(0).getOperand(0);
47822   EVT SrcVT = Src.getValueType();
47823   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
47824       !TLI.isTypeLegal(SrcVT))
47825     return SDValue();
47826 
47827   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
47828     return SDValue();
47829 
47830   // We only care about the first subvector of the concat, we expect the
47831   // other subvectors to be ignored due to the AND if we make the change.
47832   SDValue SubVec = Src.getOperand(0);
47833   EVT SubVecVT = SubVec.getValueType();
47834 
47835   // First subvector should be a setcc with a legal result type. The RHS of the
47836   // AND should be a mask with this many bits.
47837   if (SubVec.getOpcode() != ISD::SETCC || !TLI.isTypeLegal(SubVecVT) ||
47838       !N->getConstantOperandAPInt(1).isMask(SubVecVT.getVectorNumElements()))
47839     return SDValue();
47840 
47841   EVT SetccVT = SubVec.getOperand(0).getValueType();
47842   if (!TLI.isTypeLegal(SetccVT) ||
47843       !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
47844     return SDValue();
47845 
47846   if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
47847     return SDValue();
47848 
47849   // We passed all the checks. Rebuild the concat_vectors with zeroes
47850   // and cast it back to VT.
47851   SDLoc dl(N);
47852   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
47853                               DAG.getConstant(0, dl, SubVecVT));
47854   Ops[0] = SubVec;
47855   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
47856                                Ops);
47857   return DAG.getBitcast(VT, Concat);
47858 }
47859 
47860 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
47861                           TargetLowering::DAGCombinerInfo &DCI,
47862                           const X86Subtarget &Subtarget) {
47863   SDValue N0 = N->getOperand(0);
47864   SDValue N1 = N->getOperand(1);
47865   EVT VT = N->getValueType(0);
47866   SDLoc dl(N);
47867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47868 
47869   // If this is SSE1 only convert to FAND to avoid scalarization.
47870   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
47871     return DAG.getBitcast(MVT::v4i32,
47872                           DAG.getNode(X86ISD::FAND, dl, MVT::v4f32,
47873                                       DAG.getBitcast(MVT::v4f32, N0),
47874                                       DAG.getBitcast(MVT::v4f32, N1)));
47875   }
47876 
47877   // Use a 32-bit and+zext if upper bits known zero.
47878   if (VT == MVT::i64 && Subtarget.is64Bit() && !isa<ConstantSDNode>(N1)) {
47879     APInt HiMask = APInt::getHighBitsSet(64, 32);
47880     if (DAG.MaskedValueIsZero(N1, HiMask) ||
47881         DAG.MaskedValueIsZero(N0, HiMask)) {
47882       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N0);
47883       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N1);
47884       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
47885                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
47886     }
47887   }
47888 
47889   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
47890   // TODO: Support multiple SrcOps.
47891   if (VT == MVT::i1) {
47892     SmallVector<SDValue, 2> SrcOps;
47893     SmallVector<APInt, 2> SrcPartials;
47894     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
47895         SrcOps.size() == 1) {
47896       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
47897       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
47898       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
47899       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
47900         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
47901       if (Mask) {
47902         assert(SrcPartials[0].getBitWidth() == NumElts &&
47903                "Unexpected partial reduction mask");
47904         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
47905         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
47906         return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
47907       }
47908     }
47909   }
47910 
47911   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
47912     return V;
47913 
47914   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
47915     return R;
47916 
47917   if (SDValue R = combineBitOpWithShift(N, DAG))
47918     return R;
47919 
47920   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
47921     return FPLogic;
47922 
47923   if (DCI.isBeforeLegalizeOps())
47924     return SDValue();
47925 
47926   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
47927     return R;
47928 
47929   if (SDValue R = combineAndNotIntoANDNP(N, DAG))
47930     return R;
47931 
47932   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
47933     return ShiftRight;
47934 
47935   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
47936     return R;
47937 
47938   // fold (and (mul x, c1), c2) -> (mul x, (and c1, c2))
47939   // iff c2 is all/no bits mask - i.e. a select-with-zero mask.
47940   // TODO: Handle PMULDQ/PMULUDQ/VPMADDWD/VPMADDUBSW?
47941   if (VT.isVector() && getTargetConstantFromNode(N1)) {
47942     unsigned Opc0 = N0.getOpcode();
47943     if ((Opc0 == ISD::MUL || Opc0 == ISD::MULHU || Opc0 == ISD::MULHS) &&
47944         getTargetConstantFromNode(N0.getOperand(1)) &&
47945         DAG.ComputeNumSignBits(N1) == VT.getScalarSizeInBits() &&
47946         N0->hasOneUse() && N0.getOperand(1)->hasOneUse()) {
47947       SDValue MaskMul = DAG.getNode(ISD::AND, dl, VT, N0.getOperand(1), N1);
47948       return DAG.getNode(Opc0, dl, VT, N0.getOperand(0), MaskMul);
47949     }
47950   }
47951 
47952   // Fold AND(SRL(X,Y),1) -> SETCC(BT(X,Y), COND_B) iff Y is not a constant
47953   // avoids slow variable shift (moving shift amount to ECX etc.)
47954   if (isOneConstant(N1) && N0->hasOneUse()) {
47955     SDValue Src = N0;
47956     while ((Src.getOpcode() == ISD::ZERO_EXTEND ||
47957             Src.getOpcode() == ISD::TRUNCATE) &&
47958            Src.getOperand(0)->hasOneUse())
47959       Src = Src.getOperand(0);
47960     bool ContainsNOT = false;
47961     X86::CondCode X86CC = X86::COND_B;
47962     // Peek through AND(NOT(SRL(X,Y)),1).
47963     if (isBitwiseNot(Src)) {
47964       Src = Src.getOperand(0);
47965       X86CC = X86::COND_AE;
47966       ContainsNOT = true;
47967     }
47968     if (Src.getOpcode() == ISD::SRL &&
47969         !isa<ConstantSDNode>(Src.getOperand(1))) {
47970       SDValue BitNo = Src.getOperand(1);
47971       Src = Src.getOperand(0);
47972       // Peek through AND(SRL(NOT(X),Y),1).
47973       if (isBitwiseNot(Src)) {
47974         Src = Src.getOperand(0);
47975         X86CC = X86CC == X86::COND_AE ? X86::COND_B : X86::COND_AE;
47976         ContainsNOT = true;
47977       }
47978       // If we have BMI2 then SHRX should be faster for i32/i64 cases.
47979       if (!(Subtarget.hasBMI2() && !ContainsNOT && VT.getSizeInBits() >= 32))
47980         if (SDValue BT = getBT(Src, BitNo, dl, DAG))
47981           return DAG.getZExtOrTrunc(getSETCC(X86CC, BT, dl, DAG), dl, VT);
47982     }
47983   }
47984 
47985   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
47986     // Attempt to recursively combine a bitmask AND with shuffles.
47987     SDValue Op(N, 0);
47988     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47989       return Res;
47990 
47991     // If either operand is a constant mask, then only the elements that aren't
47992     // zero are actually demanded by the other operand.
47993     auto GetDemandedMasks = [&](SDValue Op) {
47994       APInt UndefElts;
47995       SmallVector<APInt> EltBits;
47996       int NumElts = VT.getVectorNumElements();
47997       int EltSizeInBits = VT.getScalarSizeInBits();
47998       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
47999       APInt DemandedElts = APInt::getAllOnes(NumElts);
48000       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
48001                                         EltBits)) {
48002         DemandedBits.clearAllBits();
48003         DemandedElts.clearAllBits();
48004         for (int I = 0; I != NumElts; ++I) {
48005           if (UndefElts[I]) {
48006             // We can't assume an undef src element gives an undef dst - the
48007             // other src might be zero.
48008             DemandedBits.setAllBits();
48009             DemandedElts.setBit(I);
48010           } else if (!EltBits[I].isZero()) {
48011             DemandedBits |= EltBits[I];
48012             DemandedElts.setBit(I);
48013           }
48014         }
48015       }
48016       return std::make_pair(DemandedBits, DemandedElts);
48017     };
48018     std::pair<APInt, APInt> Demand0 = GetDemandedMasks(N1);
48019     std::pair<APInt, APInt> Demand1 = GetDemandedMasks(N0);
48020 
48021     if (TLI.SimplifyDemandedVectorElts(N0, Demand0.second, DCI) ||
48022         TLI.SimplifyDemandedVectorElts(N1, Demand1.second, DCI) ||
48023         TLI.SimplifyDemandedBits(N0, Demand0.first, Demand0.second, DCI) ||
48024         TLI.SimplifyDemandedBits(N1, Demand1.first, Demand1.second, DCI)) {
48025       if (N->getOpcode() != ISD::DELETED_NODE)
48026         DCI.AddToWorklist(N);
48027       return SDValue(N, 0);
48028     }
48029 
48030     SDValue NewN0 = TLI.SimplifyMultipleUseDemandedBits(N0, Demand0.first,
48031                                                         Demand0.second, DAG);
48032     SDValue NewN1 = TLI.SimplifyMultipleUseDemandedBits(N1, Demand1.first,
48033                                                         Demand1.second, DAG);
48034     if (NewN0 || NewN1)
48035       return DAG.getNode(ISD::AND, dl, VT, NewN0 ? NewN0 : N0,
48036                          NewN1 ? NewN1 : N1);
48037   }
48038 
48039   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
48040   if ((VT.getScalarSizeInBits() % 8) == 0 &&
48041       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
48042       isa<ConstantSDNode>(N0.getOperand(1))) {
48043     SDValue BitMask = N1;
48044     SDValue SrcVec = N0.getOperand(0);
48045     EVT SrcVecVT = SrcVec.getValueType();
48046 
48047     // Check that the constant bitmask masks whole bytes.
48048     APInt UndefElts;
48049     SmallVector<APInt, 64> EltBits;
48050     if (VT == SrcVecVT.getScalarType() && N0->isOnlyUserOf(SrcVec.getNode()) &&
48051         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
48052         llvm::all_of(EltBits, [](const APInt &M) {
48053           return M.isZero() || M.isAllOnes();
48054         })) {
48055       unsigned NumElts = SrcVecVT.getVectorNumElements();
48056       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
48057       unsigned Idx = N0.getConstantOperandVal(1);
48058 
48059       // Create a root shuffle mask from the byte mask and the extracted index.
48060       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
48061       for (unsigned i = 0; i != Scale; ++i) {
48062         if (UndefElts[i])
48063           continue;
48064         int VecIdx = Scale * Idx + i;
48065         ShuffleMask[VecIdx] = EltBits[i].isZero() ? SM_SentinelZero : VecIdx;
48066       }
48067 
48068       if (SDValue Shuffle = combineX86ShufflesRecursively(
48069               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
48070               X86::MaxShuffleCombineDepth,
48071               /*HasVarMask*/ false, /*AllowVarCrossLaneMask*/ true,
48072               /*AllowVarPerLaneMask*/ true, DAG, Subtarget))
48073         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Shuffle,
48074                            N0.getOperand(1));
48075     }
48076   }
48077 
48078   return SDValue();
48079 }
48080 
48081 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
48082 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
48083                                      const X86Subtarget &Subtarget) {
48084   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
48085 
48086   MVT VT = N->getSimpleValueType(0);
48087   unsigned EltSizeInBits = VT.getScalarSizeInBits();
48088   if (!VT.isVector() || (EltSizeInBits % 8) != 0)
48089     return SDValue();
48090 
48091   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
48092   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
48093   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
48094     return SDValue();
48095 
48096   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
48097   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
48098   if (!(Subtarget.hasXOP() || useVPTERNLOG(Subtarget, VT) ||
48099         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
48100     return SDValue();
48101 
48102   // Attempt to extract constant byte masks.
48103   APInt UndefElts0, UndefElts1;
48104   SmallVector<APInt, 32> EltBits0, EltBits1;
48105   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
48106                                      false, false))
48107     return SDValue();
48108   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
48109                                      false, false))
48110     return SDValue();
48111 
48112   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
48113     // TODO - add UNDEF elts support.
48114     if (UndefElts0[i] || UndefElts1[i])
48115       return SDValue();
48116     if (EltBits0[i] != ~EltBits1[i])
48117       return SDValue();
48118   }
48119 
48120   SDLoc DL(N);
48121 
48122   if (useVPTERNLOG(Subtarget, VT)) {
48123     // Emit a VPTERNLOG node directly - 0xCA is the imm code for A?B:C.
48124     // VPTERNLOG is only available as vXi32/64-bit types.
48125     MVT OpSVT = EltSizeInBits == 32 ? MVT::i32 : MVT::i64;
48126     MVT OpVT =
48127         MVT::getVectorVT(OpSVT, VT.getSizeInBits() / OpSVT.getSizeInBits());
48128     SDValue A = DAG.getBitcast(OpVT, N0.getOperand(1));
48129     SDValue B = DAG.getBitcast(OpVT, N0.getOperand(0));
48130     SDValue C = DAG.getBitcast(OpVT, N1.getOperand(0));
48131     SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
48132     SDValue Res = getAVX512Node(X86ISD::VPTERNLOG, DL, OpVT, {A, B, C, Imm},
48133                                 DAG, Subtarget);
48134     return DAG.getBitcast(VT, Res);
48135   }
48136 
48137   SDValue X = N->getOperand(0);
48138   SDValue Y =
48139       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
48140                   DAG.getBitcast(VT, N1.getOperand(0)));
48141   return DAG.getNode(ISD::OR, DL, VT, X, Y);
48142 }
48143 
48144 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
48145 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
48146   if (N->getOpcode() != ISD::OR)
48147     return false;
48148 
48149   SDValue N0 = N->getOperand(0);
48150   SDValue N1 = N->getOperand(1);
48151 
48152   // Canonicalize AND to LHS.
48153   if (N1.getOpcode() == ISD::AND)
48154     std::swap(N0, N1);
48155 
48156   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
48157   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
48158     return false;
48159 
48160   Mask = N1.getOperand(0);
48161   X = N1.getOperand(1);
48162 
48163   // Check to see if the mask appeared in both the AND and ANDNP.
48164   if (N0.getOperand(0) == Mask)
48165     Y = N0.getOperand(1);
48166   else if (N0.getOperand(1) == Mask)
48167     Y = N0.getOperand(0);
48168   else
48169     return false;
48170 
48171   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
48172   // ANDNP combine allows other combines to happen that prevent matching.
48173   return true;
48174 }
48175 
48176 // Try to fold:
48177 //   (or (and (m, y), (pandn m, x)))
48178 // into:
48179 //   (vselect m, x, y)
48180 // As a special case, try to fold:
48181 //   (or (and (m, (sub 0, x)), (pandn m, x)))
48182 // into:
48183 //   (sub (xor X, M), M)
48184 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
48185                                             const X86Subtarget &Subtarget) {
48186   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
48187 
48188   EVT VT = N->getValueType(0);
48189   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
48190         (VT.is256BitVector() && Subtarget.hasInt256())))
48191     return SDValue();
48192 
48193   SDValue X, Y, Mask;
48194   if (!matchLogicBlend(N, X, Y, Mask))
48195     return SDValue();
48196 
48197   // Validate that X, Y, and Mask are bitcasts, and see through them.
48198   Mask = peekThroughBitcasts(Mask);
48199   X = peekThroughBitcasts(X);
48200   Y = peekThroughBitcasts(Y);
48201 
48202   EVT MaskVT = Mask.getValueType();
48203   unsigned EltBits = MaskVT.getScalarSizeInBits();
48204 
48205   // TODO: Attempt to handle floating point cases as well?
48206   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
48207     return SDValue();
48208 
48209   SDLoc DL(N);
48210 
48211   // Attempt to combine to conditional negate: (sub (xor X, M), M)
48212   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
48213                                                            DAG, Subtarget))
48214     return Res;
48215 
48216   // PBLENDVB is only available on SSE 4.1.
48217   if (!Subtarget.hasSSE41())
48218     return SDValue();
48219 
48220   // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
48221   if (Subtarget.hasVLX())
48222     return SDValue();
48223 
48224   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
48225 
48226   X = DAG.getBitcast(BlendVT, X);
48227   Y = DAG.getBitcast(BlendVT, Y);
48228   Mask = DAG.getBitcast(BlendVT, Mask);
48229   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
48230   return DAG.getBitcast(VT, Mask);
48231 }
48232 
48233 // Helper function for combineOrCmpEqZeroToCtlzSrl
48234 // Transforms:
48235 //   seteq(cmp x, 0)
48236 //   into:
48237 //   srl(ctlz x), log2(bitsize(x))
48238 // Input pattern is checked by caller.
48239 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) {
48240   SDValue Cmp = Op.getOperand(1);
48241   EVT VT = Cmp.getOperand(0).getValueType();
48242   unsigned Log2b = Log2_32(VT.getSizeInBits());
48243   SDLoc dl(Op);
48244   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
48245   // The result of the shift is true or false, and on X86, the 32-bit
48246   // encoding of shr and lzcnt is more desirable.
48247   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
48248   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
48249                             DAG.getConstant(Log2b, dl, MVT::i8));
48250   return Scc;
48251 }
48252 
48253 // Try to transform:
48254 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
48255 //   into:
48256 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
48257 // Will also attempt to match more generic cases, eg:
48258 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
48259 // Only applies if the target supports the FastLZCNT feature.
48260 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
48261                                            TargetLowering::DAGCombinerInfo &DCI,
48262                                            const X86Subtarget &Subtarget) {
48263   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
48264     return SDValue();
48265 
48266   auto isORCandidate = [](SDValue N) {
48267     return (N->getOpcode() == ISD::OR && N->hasOneUse());
48268   };
48269 
48270   // Check the zero extend is extending to 32-bit or more. The code generated by
48271   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
48272   // instructions to clear the upper bits.
48273   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
48274       !isORCandidate(N->getOperand(0)))
48275     return SDValue();
48276 
48277   // Check the node matches: setcc(eq, cmp 0)
48278   auto isSetCCCandidate = [](SDValue N) {
48279     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
48280            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
48281            N->getOperand(1).getOpcode() == X86ISD::CMP &&
48282            isNullConstant(N->getOperand(1).getOperand(1)) &&
48283            N->getOperand(1).getValueType().bitsGE(MVT::i32);
48284   };
48285 
48286   SDNode *OR = N->getOperand(0).getNode();
48287   SDValue LHS = OR->getOperand(0);
48288   SDValue RHS = OR->getOperand(1);
48289 
48290   // Save nodes matching or(or, setcc(eq, cmp 0)).
48291   SmallVector<SDNode *, 2> ORNodes;
48292   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
48293           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
48294     ORNodes.push_back(OR);
48295     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
48296     LHS = OR->getOperand(0);
48297     RHS = OR->getOperand(1);
48298   }
48299 
48300   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
48301   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
48302       !isORCandidate(SDValue(OR, 0)))
48303     return SDValue();
48304 
48305   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
48306   // to
48307   // or(srl(ctlz),srl(ctlz)).
48308   // The dag combiner can then fold it into:
48309   // srl(or(ctlz, ctlz)).
48310   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, DAG);
48311   SDValue Ret, NewRHS;
48312   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG)))
48313     Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, NewLHS, NewRHS);
48314 
48315   if (!Ret)
48316     return SDValue();
48317 
48318   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
48319   while (ORNodes.size() > 0) {
48320     OR = ORNodes.pop_back_val();
48321     LHS = OR->getOperand(0);
48322     RHS = OR->getOperand(1);
48323     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
48324     if (RHS->getOpcode() == ISD::OR)
48325       std::swap(LHS, RHS);
48326     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG);
48327     if (!NewRHS)
48328       return SDValue();
48329     Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, Ret, NewRHS);
48330   }
48331 
48332   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
48333 }
48334 
48335 static SDValue foldMaskedMergeImpl(SDValue And0_L, SDValue And0_R,
48336                                    SDValue And1_L, SDValue And1_R,
48337                                    const SDLoc &DL, SelectionDAG &DAG) {
48338   if (!isBitwiseNot(And0_L, true) || !And0_L->hasOneUse())
48339     return SDValue();
48340   SDValue NotOp = And0_L->getOperand(0);
48341   if (NotOp == And1_R)
48342     std::swap(And1_R, And1_L);
48343   if (NotOp != And1_L)
48344     return SDValue();
48345 
48346   // (~(NotOp) & And0_R) | (NotOp & And1_R)
48347   // --> ((And0_R ^ And1_R) & NotOp) ^ And1_R
48348   EVT VT = And1_L->getValueType(0);
48349   SDValue Freeze_And0_R = DAG.getNode(ISD::FREEZE, SDLoc(), VT, And0_R);
48350   SDValue Xor0 = DAG.getNode(ISD::XOR, DL, VT, And1_R, Freeze_And0_R);
48351   SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor0, NotOp);
48352   SDValue Xor1 = DAG.getNode(ISD::XOR, DL, VT, And, Freeze_And0_R);
48353   return Xor1;
48354 }
48355 
48356 /// Fold "masked merge" expressions like `(m & x) | (~m & y)` into the
48357 /// equivalent `((x ^ y) & m) ^ y)` pattern.
48358 /// This is typically a better representation for  targets without a fused
48359 /// "and-not" operation. This function is intended to be called from a
48360 /// `TargetLowering::PerformDAGCombine` callback on `ISD::OR` nodes.
48361 static SDValue foldMaskedMerge(SDNode *Node, SelectionDAG &DAG) {
48362   // Note that masked-merge variants using XOR or ADD expressions are
48363   // normalized to OR by InstCombine so we only check for OR.
48364   assert(Node->getOpcode() == ISD::OR && "Must be called with ISD::OR node");
48365   SDValue N0 = Node->getOperand(0);
48366   if (N0->getOpcode() != ISD::AND || !N0->hasOneUse())
48367     return SDValue();
48368   SDValue N1 = Node->getOperand(1);
48369   if (N1->getOpcode() != ISD::AND || !N1->hasOneUse())
48370     return SDValue();
48371 
48372   SDLoc DL(Node);
48373   SDValue N00 = N0->getOperand(0);
48374   SDValue N01 = N0->getOperand(1);
48375   SDValue N10 = N1->getOperand(0);
48376   SDValue N11 = N1->getOperand(1);
48377   if (SDValue Result = foldMaskedMergeImpl(N00, N01, N10, N11, DL, DAG))
48378     return Result;
48379   if (SDValue Result = foldMaskedMergeImpl(N01, N00, N10, N11, DL, DAG))
48380     return Result;
48381   if (SDValue Result = foldMaskedMergeImpl(N10, N11, N00, N01, DL, DAG))
48382     return Result;
48383   if (SDValue Result = foldMaskedMergeImpl(N11, N10, N00, N01, DL, DAG))
48384     return Result;
48385   return SDValue();
48386 }
48387 
48388 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
48389                          TargetLowering::DAGCombinerInfo &DCI,
48390                          const X86Subtarget &Subtarget) {
48391   SDValue N0 = N->getOperand(0);
48392   SDValue N1 = N->getOperand(1);
48393   EVT VT = N->getValueType(0);
48394   SDLoc dl(N);
48395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48396 
48397   // If this is SSE1 only convert to FOR to avoid scalarization.
48398   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
48399     return DAG.getBitcast(MVT::v4i32,
48400                           DAG.getNode(X86ISD::FOR, dl, MVT::v4f32,
48401                                       DAG.getBitcast(MVT::v4f32, N0),
48402                                       DAG.getBitcast(MVT::v4f32, N1)));
48403   }
48404 
48405   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
48406   // TODO: Support multiple SrcOps.
48407   if (VT == MVT::i1) {
48408     SmallVector<SDValue, 2> SrcOps;
48409     SmallVector<APInt, 2> SrcPartials;
48410     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
48411         SrcOps.size() == 1) {
48412       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
48413       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
48414       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
48415       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
48416         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
48417       if (Mask) {
48418         assert(SrcPartials[0].getBitWidth() == NumElts &&
48419                "Unexpected partial reduction mask");
48420         SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
48421         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
48422         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
48423         return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
48424       }
48425     }
48426   }
48427 
48428   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
48429     return R;
48430 
48431   if (SDValue R = combineBitOpWithShift(N, DAG))
48432     return R;
48433 
48434   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
48435     return FPLogic;
48436 
48437   if (DCI.isBeforeLegalizeOps())
48438     return SDValue();
48439 
48440   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
48441     return R;
48442 
48443   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
48444     return R;
48445 
48446   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
48447     return R;
48448 
48449   // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
48450   // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
48451   // iff the upper elements of the non-shifted arg are zero.
48452   // KUNPCK require 16+ bool vector elements.
48453   if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
48454     unsigned NumElts = VT.getVectorNumElements();
48455     unsigned HalfElts = NumElts / 2;
48456     APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
48457     if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
48458         N1.getConstantOperandAPInt(1) == HalfElts &&
48459         DAG.MaskedVectorIsZero(N0, UpperElts)) {
48460       return DAG.getNode(
48461           ISD::CONCAT_VECTORS, dl, VT,
48462           extractSubVector(N0, 0, DAG, dl, HalfElts),
48463           extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
48464     }
48465     if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
48466         N0.getConstantOperandAPInt(1) == HalfElts &&
48467         DAG.MaskedVectorIsZero(N1, UpperElts)) {
48468       return DAG.getNode(
48469           ISD::CONCAT_VECTORS, dl, VT,
48470           extractSubVector(N1, 0, DAG, dl, HalfElts),
48471           extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
48472     }
48473   }
48474 
48475   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
48476     // Attempt to recursively combine an OR of shuffles.
48477     SDValue Op(N, 0);
48478     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
48479       return Res;
48480 
48481     // If either operand is a constant mask, then only the elements that aren't
48482     // allones are actually demanded by the other operand.
48483     auto SimplifyUndemandedElts = [&](SDValue Op, SDValue OtherOp) {
48484       APInt UndefElts;
48485       SmallVector<APInt> EltBits;
48486       int NumElts = VT.getVectorNumElements();
48487       int EltSizeInBits = VT.getScalarSizeInBits();
48488       if (!getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts, EltBits))
48489         return false;
48490 
48491       APInt DemandedElts = APInt::getZero(NumElts);
48492       for (int I = 0; I != NumElts; ++I)
48493         if (!EltBits[I].isAllOnes())
48494           DemandedElts.setBit(I);
48495 
48496       return TLI.SimplifyDemandedVectorElts(OtherOp, DemandedElts, DCI);
48497     };
48498     if (SimplifyUndemandedElts(N0, N1) || SimplifyUndemandedElts(N1, N0)) {
48499       if (N->getOpcode() != ISD::DELETED_NODE)
48500         DCI.AddToWorklist(N);
48501       return SDValue(N, 0);
48502     }
48503   }
48504 
48505   // We should fold "masked merge" patterns when `andn` is not available.
48506   if (!Subtarget.hasBMI() && VT.isScalarInteger() && VT != MVT::i1)
48507     if (SDValue R = foldMaskedMerge(N, DAG))
48508       return R;
48509 
48510   return SDValue();
48511 }
48512 
48513 /// Try to turn tests against the signbit in the form of:
48514 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
48515 /// into:
48516 ///   SETGT(X, -1)
48517 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
48518   // This is only worth doing if the output type is i8 or i1.
48519   EVT ResultType = N->getValueType(0);
48520   if (ResultType != MVT::i8 && ResultType != MVT::i1)
48521     return SDValue();
48522 
48523   SDValue N0 = N->getOperand(0);
48524   SDValue N1 = N->getOperand(1);
48525 
48526   // We should be performing an xor against a truncated shift.
48527   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
48528     return SDValue();
48529 
48530   // Make sure we are performing an xor against one.
48531   if (!isOneConstant(N1))
48532     return SDValue();
48533 
48534   // SetCC on x86 zero extends so only act on this if it's a logical shift.
48535   SDValue Shift = N0.getOperand(0);
48536   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
48537     return SDValue();
48538 
48539   // Make sure we are truncating from one of i16, i32 or i64.
48540   EVT ShiftTy = Shift.getValueType();
48541   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
48542     return SDValue();
48543 
48544   // Make sure the shift amount extracts the sign bit.
48545   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
48546       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
48547     return SDValue();
48548 
48549   // Create a greater-than comparison against -1.
48550   // N.B. Using SETGE against 0 works but we want a canonical looking
48551   // comparison, using SETGT matches up with what TranslateX86CC.
48552   SDLoc DL(N);
48553   SDValue ShiftOp = Shift.getOperand(0);
48554   EVT ShiftOpTy = ShiftOp.getValueType();
48555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48556   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
48557                                                *DAG.getContext(), ResultType);
48558   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
48559                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
48560   if (SetCCResultType != ResultType)
48561     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
48562   return Cond;
48563 }
48564 
48565 /// Turn vector tests of the signbit in the form of:
48566 ///   xor (sra X, elt_size(X)-1), -1
48567 /// into:
48568 ///   pcmpgt X, -1
48569 ///
48570 /// This should be called before type legalization because the pattern may not
48571 /// persist after that.
48572 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
48573                                          const X86Subtarget &Subtarget) {
48574   EVT VT = N->getValueType(0);
48575   if (!VT.isSimple())
48576     return SDValue();
48577 
48578   switch (VT.getSimpleVT().SimpleTy) {
48579   default: return SDValue();
48580   case MVT::v16i8:
48581   case MVT::v8i16:
48582   case MVT::v4i32:
48583   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
48584   case MVT::v32i8:
48585   case MVT::v16i16:
48586   case MVT::v8i32:
48587   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
48588   }
48589 
48590   // There must be a shift right algebraic before the xor, and the xor must be a
48591   // 'not' operation.
48592   SDValue Shift = N->getOperand(0);
48593   SDValue Ones = N->getOperand(1);
48594   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
48595       !ISD::isBuildVectorAllOnes(Ones.getNode()))
48596     return SDValue();
48597 
48598   // The shift should be smearing the sign bit across each vector element.
48599   auto *ShiftAmt =
48600       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
48601   if (!ShiftAmt ||
48602       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
48603     return SDValue();
48604 
48605   // Create a greater-than comparison against -1. We don't use the more obvious
48606   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
48607   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
48608 }
48609 
48610 /// Detect patterns of truncation with unsigned saturation:
48611 ///
48612 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
48613 ///   Return the source value x to be truncated or SDValue() if the pattern was
48614 ///   not matched.
48615 ///
48616 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
48617 ///   where C1 >= 0 and C2 is unsigned max of destination type.
48618 ///
48619 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
48620 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
48621 ///
48622 ///   These two patterns are equivalent to:
48623 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
48624 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
48625 ///   pattern was not matched.
48626 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
48627                                  const SDLoc &DL) {
48628   EVT InVT = In.getValueType();
48629 
48630   // Saturation with truncation. We truncate from InVT to VT.
48631   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
48632          "Unexpected types for truncate operation");
48633 
48634   // Match min/max and return limit value as a parameter.
48635   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
48636     if (V.getOpcode() == Opcode &&
48637         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
48638       return V.getOperand(0);
48639     return SDValue();
48640   };
48641 
48642   APInt C1, C2;
48643   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
48644     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
48645     // the element size of the destination type.
48646     if (C2.isMask(VT.getScalarSizeInBits()))
48647       return UMin;
48648 
48649   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
48650     if (MatchMinMax(SMin, ISD::SMAX, C1))
48651       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
48652         return SMin;
48653 
48654   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
48655     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
48656       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
48657           C2.uge(C1)) {
48658         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
48659       }
48660 
48661   return SDValue();
48662 }
48663 
48664 /// Detect patterns of truncation with signed saturation:
48665 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
48666 ///                  signed_max_of_dest_type)) to dest_type)
48667 /// or:
48668 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
48669 ///                  signed_min_of_dest_type)) to dest_type).
48670 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
48671 /// Return the source value to be truncated or SDValue() if the pattern was not
48672 /// matched.
48673 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
48674   unsigned NumDstBits = VT.getScalarSizeInBits();
48675   unsigned NumSrcBits = In.getScalarValueSizeInBits();
48676   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
48677 
48678   auto MatchMinMax = [](SDValue V, unsigned Opcode,
48679                         const APInt &Limit) -> SDValue {
48680     APInt C;
48681     if (V.getOpcode() == Opcode &&
48682         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
48683       return V.getOperand(0);
48684     return SDValue();
48685   };
48686 
48687   APInt SignedMax, SignedMin;
48688   if (MatchPackUS) {
48689     SignedMax = APInt::getAllOnes(NumDstBits).zext(NumSrcBits);
48690     SignedMin = APInt(NumSrcBits, 0);
48691   } else {
48692     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
48693     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
48694   }
48695 
48696   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
48697     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
48698       return SMax;
48699 
48700   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
48701     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
48702       return SMin;
48703 
48704   return SDValue();
48705 }
48706 
48707 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
48708                                       SelectionDAG &DAG,
48709                                       const X86Subtarget &Subtarget) {
48710   if (!Subtarget.hasSSE2() || !VT.isVector())
48711     return SDValue();
48712 
48713   EVT SVT = VT.getVectorElementType();
48714   EVT InVT = In.getValueType();
48715   EVT InSVT = InVT.getVectorElementType();
48716 
48717   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
48718   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
48719   // and concatenate at the same time. Then we can use a final vpmovuswb to
48720   // clip to 0-255.
48721   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
48722       InVT == MVT::v16i32 && VT == MVT::v16i8) {
48723     if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
48724       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
48725       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
48726                                            DL, DAG, Subtarget);
48727       assert(Mid && "Failed to pack!");
48728       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
48729     }
48730   }
48731 
48732   // vXi32 truncate instructions are available with AVX512F.
48733   // vXi16 truncate instructions are only available with AVX512BW.
48734   // For 256-bit or smaller vectors, we require VLX.
48735   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
48736   // If the result type is 256-bits or larger and we have disable 512-bit
48737   // registers, we should go ahead and use the pack instructions if possible.
48738   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
48739                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
48740                       (InVT.getSizeInBits() > 128) &&
48741                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
48742                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
48743 
48744   if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
48745       VT.getSizeInBits() >= 64 &&
48746       (SVT == MVT::i8 || SVT == MVT::i16) &&
48747       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
48748     if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
48749       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
48750       // Only do this when the result is at least 64 bits or we'll leaving
48751       // dangling PACKSSDW nodes.
48752       if (SVT == MVT::i8 && InSVT == MVT::i32) {
48753         EVT MidVT = VT.changeVectorElementType(MVT::i16);
48754         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
48755                                              DAG, Subtarget);
48756         assert(Mid && "Failed to pack!");
48757         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
48758                                            Subtarget);
48759         assert(V && "Failed to pack!");
48760         return V;
48761       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
48762         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
48763                                       Subtarget);
48764     }
48765     if (SDValue SSatVal = detectSSatPattern(In, VT))
48766       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
48767                                     Subtarget);
48768   }
48769 
48770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48771   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
48772       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI()) &&
48773       (SVT == MVT::i32 || SVT == MVT::i16 || SVT == MVT::i8)) {
48774     unsigned TruncOpc = 0;
48775     SDValue SatVal;
48776     if (SDValue SSatVal = detectSSatPattern(In, VT)) {
48777       SatVal = SSatVal;
48778       TruncOpc = X86ISD::VTRUNCS;
48779     } else if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL)) {
48780       SatVal = USatVal;
48781       TruncOpc = X86ISD::VTRUNCUS;
48782     }
48783     if (SatVal) {
48784       unsigned ResElts = VT.getVectorNumElements();
48785       // If the input type is less than 512 bits and we don't have VLX, we need
48786       // to widen to 512 bits.
48787       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
48788         unsigned NumConcats = 512 / InVT.getSizeInBits();
48789         ResElts *= NumConcats;
48790         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
48791         ConcatOps[0] = SatVal;
48792         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
48793                                 NumConcats * InVT.getVectorNumElements());
48794         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
48795       }
48796       // Widen the result if its narrower than 128 bits.
48797       if (ResElts * SVT.getSizeInBits() < 128)
48798         ResElts = 128 / SVT.getSizeInBits();
48799       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
48800       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
48801       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
48802                          DAG.getIntPtrConstant(0, DL));
48803     }
48804   }
48805 
48806   return SDValue();
48807 }
48808 
48809 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
48810 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
48811 /// ISD::AVGCEILU (AVG) instruction.
48812 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
48813                                 const X86Subtarget &Subtarget,
48814                                 const SDLoc &DL) {
48815   if (!VT.isVector())
48816     return SDValue();
48817   EVT InVT = In.getValueType();
48818   unsigned NumElems = VT.getVectorNumElements();
48819 
48820   EVT ScalarVT = VT.getVectorElementType();
48821   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) && NumElems >= 2))
48822     return SDValue();
48823 
48824   // InScalarVT is the intermediate type in AVG pattern and it should be greater
48825   // than the original input type (i8/i16).
48826   EVT InScalarVT = InVT.getVectorElementType();
48827   if (InScalarVT.getFixedSizeInBits() <= ScalarVT.getFixedSizeInBits())
48828     return SDValue();
48829 
48830   if (!Subtarget.hasSSE2())
48831     return SDValue();
48832 
48833   // Detect the following pattern:
48834   //
48835   //   %1 = zext <N x i8> %a to <N x i32>
48836   //   %2 = zext <N x i8> %b to <N x i32>
48837   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
48838   //   %4 = add nuw nsw <N x i32> %3, %2
48839   //   %5 = lshr <N x i32> %N, <i32 1 x N>
48840   //   %6 = trunc <N x i32> %5 to <N x i8>
48841   //
48842   // In AVX512, the last instruction can also be a trunc store.
48843   if (In.getOpcode() != ISD::SRL)
48844     return SDValue();
48845 
48846   // A lambda checking the given SDValue is a constant vector and each element
48847   // is in the range [Min, Max].
48848   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
48849     return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
48850       return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
48851     });
48852   };
48853 
48854   auto IsZExtLike = [DAG = &DAG, ScalarVT](SDValue V) {
48855     unsigned MaxActiveBits = DAG->computeKnownBits(V).countMaxActiveBits();
48856     return MaxActiveBits <= ScalarVT.getSizeInBits();
48857   };
48858 
48859   // Check if each element of the vector is right-shifted by one.
48860   SDValue LHS = In.getOperand(0);
48861   SDValue RHS = In.getOperand(1);
48862   if (!IsConstVectorInRange(RHS, 1, 1))
48863     return SDValue();
48864   if (LHS.getOpcode() != ISD::ADD)
48865     return SDValue();
48866 
48867   // Detect a pattern of a + b + 1 where the order doesn't matter.
48868   SDValue Operands[3];
48869   Operands[0] = LHS.getOperand(0);
48870   Operands[1] = LHS.getOperand(1);
48871 
48872   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48873                        ArrayRef<SDValue> Ops) {
48874     return DAG.getNode(ISD::AVGCEILU, DL, Ops[0].getValueType(), Ops);
48875   };
48876 
48877   auto AVGSplitter = [&](std::array<SDValue, 2> Ops) {
48878     for (SDValue &Op : Ops)
48879       if (Op.getValueType() != VT)
48880         Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
48881     // Pad to a power-of-2 vector, split+apply and extract the original vector.
48882     unsigned NumElemsPow2 = PowerOf2Ceil(NumElems);
48883     EVT Pow2VT = EVT::getVectorVT(*DAG.getContext(), ScalarVT, NumElemsPow2);
48884     if (NumElemsPow2 != NumElems) {
48885       for (SDValue &Op : Ops) {
48886         SmallVector<SDValue, 32> EltsOfOp(NumElemsPow2, DAG.getUNDEF(ScalarVT));
48887         for (unsigned i = 0; i != NumElems; ++i) {
48888           SDValue Idx = DAG.getIntPtrConstant(i, DL);
48889           EltsOfOp[i] =
48890               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op, Idx);
48891         }
48892         Op = DAG.getBuildVector(Pow2VT, DL, EltsOfOp);
48893       }
48894     }
48895     SDValue Res = SplitOpsAndApply(DAG, Subtarget, DL, Pow2VT, Ops, AVGBuilder);
48896     if (NumElemsPow2 == NumElems)
48897       return Res;
48898     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
48899                        DAG.getIntPtrConstant(0, DL));
48900   };
48901 
48902   // Take care of the case when one of the operands is a constant vector whose
48903   // element is in the range [1, 256].
48904   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
48905       IsZExtLike(Operands[0])) {
48906     // The pattern is detected. Subtract one from the constant vector, then
48907     // demote it and emit X86ISD::AVG instruction.
48908     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
48909     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
48910     return AVGSplitter({Operands[0], Operands[1]});
48911   }
48912 
48913   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
48914   // Match the or case only if its 'add-like' - can be replaced by an add.
48915   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
48916     if (ISD::ADD == V.getOpcode()) {
48917       Op0 = V.getOperand(0);
48918       Op1 = V.getOperand(1);
48919       return true;
48920     }
48921     if (ISD::ZERO_EXTEND != V.getOpcode())
48922       return false;
48923     V = V.getOperand(0);
48924     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
48925         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
48926       return false;
48927     Op0 = V.getOperand(0);
48928     Op1 = V.getOperand(1);
48929     return true;
48930   };
48931 
48932   SDValue Op0, Op1;
48933   if (FindAddLike(Operands[0], Op0, Op1))
48934     std::swap(Operands[0], Operands[1]);
48935   else if (!FindAddLike(Operands[1], Op0, Op1))
48936     return SDValue();
48937   Operands[2] = Op0;
48938   Operands[1] = Op1;
48939 
48940   // Now we have three operands of two additions. Check that one of them is a
48941   // constant vector with ones, and the other two can be promoted from i8/i16.
48942   for (int i = 0; i < 3; ++i) {
48943     if (!IsConstVectorInRange(Operands[i], 1, 1))
48944       continue;
48945     std::swap(Operands[i], Operands[2]);
48946 
48947     // Check if Operands[0] and Operands[1] are results of type promotion.
48948     for (int j = 0; j < 2; ++j)
48949       if (Operands[j].getValueType() != VT)
48950         if (!IsZExtLike(Operands[j]))
48951           return SDValue();
48952 
48953     // The pattern is detected, emit X86ISD::AVG instruction(s).
48954     return AVGSplitter({Operands[0], Operands[1]});
48955   }
48956 
48957   return SDValue();
48958 }
48959 
48960 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
48961                            TargetLowering::DAGCombinerInfo &DCI,
48962                            const X86Subtarget &Subtarget) {
48963   LoadSDNode *Ld = cast<LoadSDNode>(N);
48964   EVT RegVT = Ld->getValueType(0);
48965   EVT MemVT = Ld->getMemoryVT();
48966   SDLoc dl(Ld);
48967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48968 
48969   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
48970   // into two 16-byte operations. Also split non-temporal aligned loads on
48971   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
48972   ISD::LoadExtType Ext = Ld->getExtensionType();
48973   bool Fast;
48974   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
48975       Ext == ISD::NON_EXTLOAD &&
48976       ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
48977         Ld->getAlign() >= Align(16)) ||
48978        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
48979                                *Ld->getMemOperand(), &Fast) &&
48980         !Fast))) {
48981     unsigned NumElems = RegVT.getVectorNumElements();
48982     if (NumElems < 2)
48983       return SDValue();
48984 
48985     unsigned HalfOffset = 16;
48986     SDValue Ptr1 = Ld->getBasePtr();
48987     SDValue Ptr2 =
48988         DAG.getMemBasePlusOffset(Ptr1, TypeSize::Fixed(HalfOffset), dl);
48989     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
48990                                   NumElems / 2);
48991     SDValue Load1 =
48992         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
48993                     Ld->getOriginalAlign(),
48994                     Ld->getMemOperand()->getFlags());
48995     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
48996                                 Ld->getPointerInfo().getWithOffset(HalfOffset),
48997                                 Ld->getOriginalAlign(),
48998                                 Ld->getMemOperand()->getFlags());
48999     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
49000                              Load1.getValue(1), Load2.getValue(1));
49001 
49002     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
49003     return DCI.CombineTo(N, NewVec, TF, true);
49004   }
49005 
49006   // Bool vector load - attempt to cast to an integer, as we have good
49007   // (vXiY *ext(vXi1 bitcast(iX))) handling.
49008   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
49009       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
49010     unsigned NumElts = RegVT.getVectorNumElements();
49011     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
49012     if (TLI.isTypeLegal(IntVT)) {
49013       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
49014                                     Ld->getPointerInfo(),
49015                                     Ld->getOriginalAlign(),
49016                                     Ld->getMemOperand()->getFlags());
49017       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
49018       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
49019     }
49020   }
49021 
49022   // If we also broadcast this as a subvector to a wider type, then just extract
49023   // the lowest subvector.
49024   if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
49025       (RegVT.is128BitVector() || RegVT.is256BitVector())) {
49026     SDValue Ptr = Ld->getBasePtr();
49027     SDValue Chain = Ld->getChain();
49028     for (SDNode *User : Ptr->uses()) {
49029       if (User != N && User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
49030           cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
49031           cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
49032           cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
49033               MemVT.getSizeInBits() &&
49034           !User->hasAnyUseOfValue(1) &&
49035           User->getValueSizeInBits(0).getFixedSize() >
49036               RegVT.getFixedSizeInBits()) {
49037         SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
49038                                            RegVT.getSizeInBits());
49039         Extract = DAG.getBitcast(RegVT, Extract);
49040         return DCI.CombineTo(N, Extract, SDValue(User, 1));
49041       }
49042     }
49043   }
49044 
49045   // Cast ptr32 and ptr64 pointers to the default address space before a load.
49046   unsigned AddrSpace = Ld->getAddressSpace();
49047   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
49048       AddrSpace == X86AS::PTR32_UPTR) {
49049     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
49050     if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
49051       SDValue Cast =
49052           DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
49053       return DAG.getLoad(RegVT, dl, Ld->getChain(), Cast, Ld->getPointerInfo(),
49054                          Ld->getOriginalAlign(),
49055                          Ld->getMemOperand()->getFlags());
49056     }
49057   }
49058 
49059   return SDValue();
49060 }
49061 
49062 /// If V is a build vector of boolean constants and exactly one of those
49063 /// constants is true, return the operand index of that true element.
49064 /// Otherwise, return -1.
49065 static int getOneTrueElt(SDValue V) {
49066   // This needs to be a build vector of booleans.
49067   // TODO: Checking for the i1 type matches the IR definition for the mask,
49068   // but the mask check could be loosened to i8 or other types. That might
49069   // also require checking more than 'allOnesValue'; eg, the x86 HW
49070   // instructions only require that the MSB is set for each mask element.
49071   // The ISD::MSTORE comments/definition do not specify how the mask operand
49072   // is formatted.
49073   auto *BV = dyn_cast<BuildVectorSDNode>(V);
49074   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
49075     return -1;
49076 
49077   int TrueIndex = -1;
49078   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
49079   for (unsigned i = 0; i < NumElts; ++i) {
49080     const SDValue &Op = BV->getOperand(i);
49081     if (Op.isUndef())
49082       continue;
49083     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
49084     if (!ConstNode)
49085       return -1;
49086     if (ConstNode->getAPIntValue().countTrailingOnes() >= 1) {
49087       // If we already found a one, this is too many.
49088       if (TrueIndex >= 0)
49089         return -1;
49090       TrueIndex = i;
49091     }
49092   }
49093   return TrueIndex;
49094 }
49095 
49096 /// Given a masked memory load/store operation, return true if it has one mask
49097 /// bit set. If it has one mask bit set, then also return the memory address of
49098 /// the scalar element to load/store, the vector index to insert/extract that
49099 /// scalar element, and the alignment for the scalar memory access.
49100 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
49101                                          SelectionDAG &DAG, SDValue &Addr,
49102                                          SDValue &Index, Align &Alignment,
49103                                          unsigned &Offset) {
49104   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
49105   if (TrueMaskElt < 0)
49106     return false;
49107 
49108   // Get the address of the one scalar element that is specified by the mask
49109   // using the appropriate offset from the base pointer.
49110   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
49111   Offset = 0;
49112   Addr = MaskedOp->getBasePtr();
49113   if (TrueMaskElt != 0) {
49114     Offset = TrueMaskElt * EltVT.getStoreSize();
49115     Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::Fixed(Offset),
49116                                     SDLoc(MaskedOp));
49117   }
49118 
49119   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
49120   Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
49121                               EltVT.getStoreSize());
49122   return true;
49123 }
49124 
49125 /// If exactly one element of the mask is set for a non-extending masked load,
49126 /// it is a scalar load and vector insert.
49127 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
49128 /// mask have already been optimized in IR, so we don't bother with those here.
49129 static SDValue
49130 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
49131                              TargetLowering::DAGCombinerInfo &DCI,
49132                              const X86Subtarget &Subtarget) {
49133   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
49134   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
49135   // However, some target hooks may need to be added to know when the transform
49136   // is profitable. Endianness would also have to be considered.
49137 
49138   SDValue Addr, VecIndex;
49139   Align Alignment;
49140   unsigned Offset;
49141   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
49142     return SDValue();
49143 
49144   // Load the one scalar element that is specified by the mask using the
49145   // appropriate offset from the base pointer.
49146   SDLoc DL(ML);
49147   EVT VT = ML->getValueType(0);
49148   EVT EltVT = VT.getVectorElementType();
49149 
49150   EVT CastVT = VT;
49151   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
49152     EltVT = MVT::f64;
49153     CastVT = VT.changeVectorElementType(EltVT);
49154   }
49155 
49156   SDValue Load =
49157       DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
49158                   ML->getPointerInfo().getWithOffset(Offset),
49159                   Alignment, ML->getMemOperand()->getFlags());
49160 
49161   SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
49162 
49163   // Insert the loaded element into the appropriate place in the vector.
49164   SDValue Insert =
49165       DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
49166   Insert = DAG.getBitcast(VT, Insert);
49167   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
49168 }
49169 
49170 static SDValue
49171 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
49172                               TargetLowering::DAGCombinerInfo &DCI) {
49173   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
49174   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
49175     return SDValue();
49176 
49177   SDLoc DL(ML);
49178   EVT VT = ML->getValueType(0);
49179 
49180   // If we are loading the first and last elements of a vector, it is safe and
49181   // always faster to load the whole vector. Replace the masked load with a
49182   // vector load and select.
49183   unsigned NumElts = VT.getVectorNumElements();
49184   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
49185   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
49186   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
49187   if (LoadFirstElt && LoadLastElt) {
49188     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
49189                                 ML->getMemOperand());
49190     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
49191                                   ML->getPassThru());
49192     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
49193   }
49194 
49195   // Convert a masked load with a constant mask into a masked load and a select.
49196   // This allows the select operation to use a faster kind of select instruction
49197   // (for example, vblendvps -> vblendps).
49198 
49199   // Don't try this if the pass-through operand is already undefined. That would
49200   // cause an infinite loop because that's what we're about to create.
49201   if (ML->getPassThru().isUndef())
49202     return SDValue();
49203 
49204   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
49205     return SDValue();
49206 
49207   // The new masked load has an undef pass-through operand. The select uses the
49208   // original pass-through operand.
49209   SDValue NewML = DAG.getMaskedLoad(
49210       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
49211       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
49212       ML->getAddressingMode(), ML->getExtensionType());
49213   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
49214                                 ML->getPassThru());
49215 
49216   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
49217 }
49218 
49219 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
49220                                  TargetLowering::DAGCombinerInfo &DCI,
49221                                  const X86Subtarget &Subtarget) {
49222   auto *Mld = cast<MaskedLoadSDNode>(N);
49223 
49224   // TODO: Expanding load with constant mask may be optimized as well.
49225   if (Mld->isExpandingLoad())
49226     return SDValue();
49227 
49228   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
49229     if (SDValue ScalarLoad =
49230             reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
49231       return ScalarLoad;
49232 
49233     // TODO: Do some AVX512 subsets benefit from this transform?
49234     if (!Subtarget.hasAVX512())
49235       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
49236         return Blend;
49237   }
49238 
49239   // If the mask value has been legalized to a non-boolean vector, try to
49240   // simplify ops leading up to it. We only demand the MSB of each lane.
49241   SDValue Mask = Mld->getMask();
49242   if (Mask.getScalarValueSizeInBits() != 1) {
49243     EVT VT = Mld->getValueType(0);
49244     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49245     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
49246     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
49247       if (N->getOpcode() != ISD::DELETED_NODE)
49248         DCI.AddToWorklist(N);
49249       return SDValue(N, 0);
49250     }
49251     if (SDValue NewMask =
49252             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
49253       return DAG.getMaskedLoad(
49254           VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
49255           NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
49256           Mld->getAddressingMode(), Mld->getExtensionType());
49257   }
49258 
49259   return SDValue();
49260 }
49261 
49262 /// If exactly one element of the mask is set for a non-truncating masked store,
49263 /// it is a vector extract and scalar store.
49264 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
49265 /// mask have already been optimized in IR, so we don't bother with those here.
49266 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
49267                                               SelectionDAG &DAG,
49268                                               const X86Subtarget &Subtarget) {
49269   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
49270   // However, some target hooks may need to be added to know when the transform
49271   // is profitable. Endianness would also have to be considered.
49272 
49273   SDValue Addr, VecIndex;
49274   Align Alignment;
49275   unsigned Offset;
49276   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
49277     return SDValue();
49278 
49279   // Extract the one scalar element that is actually being stored.
49280   SDLoc DL(MS);
49281   SDValue Value = MS->getValue();
49282   EVT VT = Value.getValueType();
49283   EVT EltVT = VT.getVectorElementType();
49284   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
49285     EltVT = MVT::f64;
49286     EVT CastVT = VT.changeVectorElementType(EltVT);
49287     Value = DAG.getBitcast(CastVT, Value);
49288   }
49289   SDValue Extract =
49290       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
49291 
49292   // Store that element at the appropriate offset from the base pointer.
49293   return DAG.getStore(MS->getChain(), DL, Extract, Addr,
49294                       MS->getPointerInfo().getWithOffset(Offset),
49295                       Alignment, MS->getMemOperand()->getFlags());
49296 }
49297 
49298 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
49299                                   TargetLowering::DAGCombinerInfo &DCI,
49300                                   const X86Subtarget &Subtarget) {
49301   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
49302   if (Mst->isCompressingStore())
49303     return SDValue();
49304 
49305   EVT VT = Mst->getValue().getValueType();
49306   SDLoc dl(Mst);
49307   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49308 
49309   if (Mst->isTruncatingStore())
49310     return SDValue();
49311 
49312   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
49313     return ScalarStore;
49314 
49315   // If the mask value has been legalized to a non-boolean vector, try to
49316   // simplify ops leading up to it. We only demand the MSB of each lane.
49317   SDValue Mask = Mst->getMask();
49318   if (Mask.getScalarValueSizeInBits() != 1) {
49319     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
49320     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
49321       if (N->getOpcode() != ISD::DELETED_NODE)
49322         DCI.AddToWorklist(N);
49323       return SDValue(N, 0);
49324     }
49325     if (SDValue NewMask =
49326             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
49327       return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
49328                                 Mst->getBasePtr(), Mst->getOffset(), NewMask,
49329                                 Mst->getMemoryVT(), Mst->getMemOperand(),
49330                                 Mst->getAddressingMode());
49331   }
49332 
49333   SDValue Value = Mst->getValue();
49334   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
49335       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
49336                             Mst->getMemoryVT())) {
49337     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
49338                               Mst->getBasePtr(), Mst->getOffset(), Mask,
49339                               Mst->getMemoryVT(), Mst->getMemOperand(),
49340                               Mst->getAddressingMode(), true);
49341   }
49342 
49343   return SDValue();
49344 }
49345 
49346 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
49347                             TargetLowering::DAGCombinerInfo &DCI,
49348                             const X86Subtarget &Subtarget) {
49349   StoreSDNode *St = cast<StoreSDNode>(N);
49350   EVT StVT = St->getMemoryVT();
49351   SDLoc dl(St);
49352   SDValue StoredVal = St->getValue();
49353   EVT VT = StoredVal.getValueType();
49354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49355 
49356   // Convert a store of vXi1 into a store of iX and a bitcast.
49357   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
49358       VT.getVectorElementType() == MVT::i1) {
49359 
49360     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
49361     StoredVal = DAG.getBitcast(NewVT, StoredVal);
49362 
49363     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
49364                         St->getPointerInfo(), St->getOriginalAlign(),
49365                         St->getMemOperand()->getFlags());
49366   }
49367 
49368   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
49369   // This will avoid a copy to k-register.
49370   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
49371       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
49372       StoredVal.getOperand(0).getValueType() == MVT::i8) {
49373     SDValue Val = StoredVal.getOperand(0);
49374     // We must store zeros to the unused bits.
49375     Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
49376     return DAG.getStore(St->getChain(), dl, Val,
49377                         St->getBasePtr(), St->getPointerInfo(),
49378                         St->getOriginalAlign(),
49379                         St->getMemOperand()->getFlags());
49380   }
49381 
49382   // Widen v2i1/v4i1 stores to v8i1.
49383   if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
49384       Subtarget.hasAVX512()) {
49385     unsigned NumConcats = 8 / VT.getVectorNumElements();
49386     // We must store zeros to the unused bits.
49387     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
49388     Ops[0] = StoredVal;
49389     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
49390     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
49391                         St->getPointerInfo(), St->getOriginalAlign(),
49392                         St->getMemOperand()->getFlags());
49393   }
49394 
49395   // Turn vXi1 stores of constants into a scalar store.
49396   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
49397        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
49398       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
49399     // If its a v64i1 store without 64-bit support, we need two stores.
49400     if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
49401       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
49402                                       StoredVal->ops().slice(0, 32));
49403       Lo = combinevXi1ConstantToInteger(Lo, DAG);
49404       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
49405                                       StoredVal->ops().slice(32, 32));
49406       Hi = combinevXi1ConstantToInteger(Hi, DAG);
49407 
49408       SDValue Ptr0 = St->getBasePtr();
49409       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(4), dl);
49410 
49411       SDValue Ch0 =
49412           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
49413                        St->getOriginalAlign(),
49414                        St->getMemOperand()->getFlags());
49415       SDValue Ch1 =
49416           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
49417                        St->getPointerInfo().getWithOffset(4),
49418                        St->getOriginalAlign(),
49419                        St->getMemOperand()->getFlags());
49420       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
49421     }
49422 
49423     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
49424     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
49425                         St->getPointerInfo(), St->getOriginalAlign(),
49426                         St->getMemOperand()->getFlags());
49427   }
49428 
49429   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
49430   // Sandy Bridge, perform two 16-byte stores.
49431   bool Fast;
49432   if (VT.is256BitVector() && StVT == VT &&
49433       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
49434                              *St->getMemOperand(), &Fast) &&
49435       !Fast) {
49436     unsigned NumElems = VT.getVectorNumElements();
49437     if (NumElems < 2)
49438       return SDValue();
49439 
49440     return splitVectorStore(St, DAG);
49441   }
49442 
49443   // Split under-aligned vector non-temporal stores.
49444   if (St->isNonTemporal() && StVT == VT &&
49445       St->getAlign().value() < VT.getStoreSize()) {
49446     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
49447     // vectors or the legalizer can scalarize it to use MOVNTI.
49448     if (VT.is256BitVector() || VT.is512BitVector()) {
49449       unsigned NumElems = VT.getVectorNumElements();
49450       if (NumElems < 2)
49451         return SDValue();
49452       return splitVectorStore(St, DAG);
49453     }
49454 
49455     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
49456     // to use MOVNTI.
49457     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
49458       MVT NTVT = Subtarget.hasSSE4A()
49459                      ? MVT::v2f64
49460                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
49461       return scalarizeVectorStore(St, NTVT, DAG);
49462     }
49463   }
49464 
49465   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
49466   // supported, but avx512f is by extending to v16i32 and truncating.
49467   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
49468       St->getValue().getOpcode() == ISD::TRUNCATE &&
49469       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
49470       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
49471       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
49472     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32,
49473                               St->getValue().getOperand(0));
49474     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
49475                              MVT::v16i8, St->getMemOperand());
49476   }
49477 
49478   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
49479   if (!St->isTruncatingStore() &&
49480       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
49481        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
49482       StoredVal.hasOneUse() &&
49483       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
49484     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
49485     return EmitTruncSStore(IsSigned, St->getChain(),
49486                            dl, StoredVal.getOperand(0), St->getBasePtr(),
49487                            VT, St->getMemOperand(), DAG);
49488   }
49489 
49490   // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
49491   if (!St->isTruncatingStore()) {
49492     auto IsExtractedElement = [](SDValue V) {
49493       if (V.getOpcode() == ISD::TRUNCATE && V.hasOneUse())
49494         V = V.getOperand(0);
49495       unsigned Opc = V.getOpcode();
49496       if ((Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) &&
49497           isNullConstant(V.getOperand(1)) && V.hasOneUse() &&
49498           V.getOperand(0).hasOneUse())
49499         return V.getOperand(0);
49500       return SDValue();
49501     };
49502     if (SDValue Extract = IsExtractedElement(StoredVal)) {
49503       SDValue Trunc = peekThroughOneUseBitcasts(Extract);
49504       if (Trunc.getOpcode() == X86ISD::VTRUNC) {
49505         SDValue Src = Trunc.getOperand(0);
49506         MVT DstVT = Trunc.getSimpleValueType();
49507         MVT SrcVT = Src.getSimpleValueType();
49508         unsigned NumSrcElts = SrcVT.getVectorNumElements();
49509         unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
49510         MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
49511         if (NumTruncBits == VT.getSizeInBits() &&
49512             TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
49513           return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
49514                                    TruncVT, St->getMemOperand());
49515         }
49516       }
49517     }
49518   }
49519 
49520   // Optimize trunc store (of multiple scalars) to shuffle and store.
49521   // First, pack all of the elements in one place. Next, store to memory
49522   // in fewer chunks.
49523   if (St->isTruncatingStore() && VT.isVector()) {
49524     // Check if we can detect an AVG pattern from the truncation. If yes,
49525     // replace the trunc store by a normal store with the result of X86ISD::AVG
49526     // instruction.
49527     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
49528       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
49529                                          Subtarget, dl))
49530         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
49531                             St->getPointerInfo(), St->getOriginalAlign(),
49532                             St->getMemOperand()->getFlags());
49533 
49534     if (TLI.isTruncStoreLegal(VT, StVT)) {
49535       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
49536         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
49537                                dl, Val, St->getBasePtr(),
49538                                St->getMemoryVT(), St->getMemOperand(), DAG);
49539       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
49540                                           DAG, dl))
49541         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
49542                                dl, Val, St->getBasePtr(),
49543                                St->getMemoryVT(), St->getMemOperand(), DAG);
49544     }
49545 
49546     return SDValue();
49547   }
49548 
49549   // Cast ptr32 and ptr64 pointers to the default address space before a store.
49550   unsigned AddrSpace = St->getAddressSpace();
49551   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
49552       AddrSpace == X86AS::PTR32_UPTR) {
49553     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
49554     if (PtrVT != St->getBasePtr().getSimpleValueType()) {
49555       SDValue Cast =
49556           DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
49557       return DAG.getStore(St->getChain(), dl, StoredVal, Cast,
49558                           St->getPointerInfo(), St->getOriginalAlign(),
49559                           St->getMemOperand()->getFlags(), St->getAAInfo());
49560     }
49561   }
49562 
49563   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
49564   // the FP state in cases where an emms may be missing.
49565   // A preferable solution to the general problem is to figure out the right
49566   // places to insert EMMS.  This qualifies as a quick hack.
49567 
49568   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
49569   if (VT.getSizeInBits() != 64)
49570     return SDValue();
49571 
49572   const Function &F = DAG.getMachineFunction().getFunction();
49573   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
49574   bool F64IsLegal =
49575       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
49576   if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
49577       isa<LoadSDNode>(St->getValue()) &&
49578       cast<LoadSDNode>(St->getValue())->isSimple() &&
49579       St->getChain().hasOneUse() && St->isSimple()) {
49580     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
49581 
49582     if (!ISD::isNormalLoad(Ld))
49583       return SDValue();
49584 
49585     // Avoid the transformation if there are multiple uses of the loaded value.
49586     if (!Ld->hasNUsesOfValue(1, 0))
49587       return SDValue();
49588 
49589     SDLoc LdDL(Ld);
49590     SDLoc StDL(N);
49591     // Lower to a single movq load/store pair.
49592     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
49593                                 Ld->getBasePtr(), Ld->getMemOperand());
49594 
49595     // Make sure new load is placed in same chain order.
49596     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
49597     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
49598                         St->getMemOperand());
49599   }
49600 
49601   // This is similar to the above case, but here we handle a scalar 64-bit
49602   // integer store that is extracted from a vector on a 32-bit target.
49603   // If we have SSE2, then we can treat it like a floating-point double
49604   // to get past legalization. The execution dependencies fixup pass will
49605   // choose the optimal machine instruction for the store if this really is
49606   // an integer or v2f32 rather than an f64.
49607   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
49608       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
49609     SDValue OldExtract = St->getOperand(1);
49610     SDValue ExtOp0 = OldExtract.getOperand(0);
49611     unsigned VecSize = ExtOp0.getValueSizeInBits();
49612     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
49613     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
49614     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
49615                                      BitCast, OldExtract.getOperand(1));
49616     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
49617                         St->getPointerInfo(), St->getOriginalAlign(),
49618                         St->getMemOperand()->getFlags());
49619   }
49620 
49621   return SDValue();
49622 }
49623 
49624 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
49625                                      TargetLowering::DAGCombinerInfo &DCI,
49626                                      const X86Subtarget &Subtarget) {
49627   auto *St = cast<MemIntrinsicSDNode>(N);
49628 
49629   SDValue StoredVal = N->getOperand(1);
49630   MVT VT = StoredVal.getSimpleValueType();
49631   EVT MemVT = St->getMemoryVT();
49632 
49633   // Figure out which elements we demand.
49634   unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
49635   APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
49636 
49637   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49638   if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, DCI)) {
49639     if (N->getOpcode() != ISD::DELETED_NODE)
49640       DCI.AddToWorklist(N);
49641     return SDValue(N, 0);
49642   }
49643 
49644   return SDValue();
49645 }
49646 
49647 /// Return 'true' if this vector operation is "horizontal"
49648 /// and return the operands for the horizontal operation in LHS and RHS.  A
49649 /// horizontal operation performs the binary operation on successive elements
49650 /// of its first operand, then on successive elements of its second operand,
49651 /// returning the resulting values in a vector.  For example, if
49652 ///   A = < float a0, float a1, float a2, float a3 >
49653 /// and
49654 ///   B = < float b0, float b1, float b2, float b3 >
49655 /// then the result of doing a horizontal operation on A and B is
49656 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
49657 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
49658 /// A horizontal-op B, for some already available A and B, and if so then LHS is
49659 /// set to A, RHS to B, and the routine returns 'true'.
49660 static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
49661                               SelectionDAG &DAG, const X86Subtarget &Subtarget,
49662                               bool IsCommutative,
49663                               SmallVectorImpl<int> &PostShuffleMask) {
49664   // If either operand is undef, bail out. The binop should be simplified.
49665   if (LHS.isUndef() || RHS.isUndef())
49666     return false;
49667 
49668   // Look for the following pattern:
49669   //   A = < float a0, float a1, float a2, float a3 >
49670   //   B = < float b0, float b1, float b2, float b3 >
49671   // and
49672   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
49673   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
49674   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
49675   // which is A horizontal-op B.
49676 
49677   MVT VT = LHS.getSimpleValueType();
49678   assert((VT.is128BitVector() || VT.is256BitVector()) &&
49679          "Unsupported vector type for horizontal add/sub");
49680   unsigned NumElts = VT.getVectorNumElements();
49681 
49682   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
49683                         SmallVectorImpl<int> &ShuffleMask) {
49684     bool UseSubVector = false;
49685     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
49686         Op.getOperand(0).getValueType().is256BitVector() &&
49687         llvm::isNullConstant(Op.getOperand(1))) {
49688       Op = Op.getOperand(0);
49689       UseSubVector = true;
49690     }
49691     SmallVector<SDValue, 2> SrcOps;
49692     SmallVector<int, 16> SrcMask, ScaledMask;
49693     SDValue BC = peekThroughBitcasts(Op);
49694     if (getTargetShuffleInputs(BC, SrcOps, SrcMask, DAG) &&
49695         !isAnyZero(SrcMask) && all_of(SrcOps, [BC](SDValue Op) {
49696           return Op.getValueSizeInBits() == BC.getValueSizeInBits();
49697         })) {
49698       resolveTargetShuffleInputsAndMask(SrcOps, SrcMask);
49699       if (!UseSubVector && SrcOps.size() <= 2 &&
49700           scaleShuffleElements(SrcMask, NumElts, ScaledMask)) {
49701         N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
49702         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
49703         ShuffleMask.assign(ScaledMask.begin(), ScaledMask.end());
49704       }
49705       if (UseSubVector && SrcOps.size() == 1 &&
49706           scaleShuffleElements(SrcMask, 2 * NumElts, ScaledMask)) {
49707         std::tie(N0, N1) = DAG.SplitVector(SrcOps[0], SDLoc(Op));
49708         ArrayRef<int> Mask = ArrayRef<int>(ScaledMask).slice(0, NumElts);
49709         ShuffleMask.assign(Mask.begin(), Mask.end());
49710       }
49711     }
49712   };
49713 
49714   // View LHS in the form
49715   //   LHS = VECTOR_SHUFFLE A, B, LMask
49716   // If LHS is not a shuffle, then pretend it is the identity shuffle:
49717   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
49718   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
49719   SDValue A, B;
49720   SmallVector<int, 16> LMask;
49721   GetShuffle(LHS, A, B, LMask);
49722 
49723   // Likewise, view RHS in the form
49724   //   RHS = VECTOR_SHUFFLE C, D, RMask
49725   SDValue C, D;
49726   SmallVector<int, 16> RMask;
49727   GetShuffle(RHS, C, D, RMask);
49728 
49729   // At least one of the operands should be a vector shuffle.
49730   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
49731   if (NumShuffles == 0)
49732     return false;
49733 
49734   if (LMask.empty()) {
49735     A = LHS;
49736     for (unsigned i = 0; i != NumElts; ++i)
49737       LMask.push_back(i);
49738   }
49739 
49740   if (RMask.empty()) {
49741     C = RHS;
49742     for (unsigned i = 0; i != NumElts; ++i)
49743       RMask.push_back(i);
49744   }
49745 
49746   // If we have an unary mask, ensure the other op is set to null.
49747   if (isUndefOrInRange(LMask, 0, NumElts))
49748     B = SDValue();
49749   else if (isUndefOrInRange(LMask, NumElts, NumElts * 2))
49750     A = SDValue();
49751 
49752   if (isUndefOrInRange(RMask, 0, NumElts))
49753     D = SDValue();
49754   else if (isUndefOrInRange(RMask, NumElts, NumElts * 2))
49755     C = SDValue();
49756 
49757   // If A and B occur in reverse order in RHS, then canonicalize by commuting
49758   // RHS operands and shuffle mask.
49759   if (A != C) {
49760     std::swap(C, D);
49761     ShuffleVectorSDNode::commuteMask(RMask);
49762   }
49763   // Check that the shuffles are both shuffling the same vectors.
49764   if (!(A == C && B == D))
49765     return false;
49766 
49767   PostShuffleMask.clear();
49768   PostShuffleMask.append(NumElts, SM_SentinelUndef);
49769 
49770   // LHS and RHS are now:
49771   //   LHS = shuffle A, B, LMask
49772   //   RHS = shuffle A, B, RMask
49773   // Check that the masks correspond to performing a horizontal operation.
49774   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
49775   // so we just repeat the inner loop if this is a 256-bit op.
49776   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
49777   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
49778   unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
49779   assert((NumEltsPer128BitChunk % 2 == 0) &&
49780          "Vector type should have an even number of elements in each lane");
49781   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
49782     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
49783       // Ignore undefined components.
49784       int LIdx = LMask[i + j], RIdx = RMask[i + j];
49785       if (LIdx < 0 || RIdx < 0 ||
49786           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
49787           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
49788         continue;
49789 
49790       // Check that successive odd/even elements are being operated on. If not,
49791       // this is not a horizontal operation.
49792       if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
49793           !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
49794         return false;
49795 
49796       // Compute the post-shuffle mask index based on where the element
49797       // is stored in the HOP result, and where it needs to be moved to.
49798       int Base = LIdx & ~1u;
49799       int Index = ((Base % NumEltsPer128BitChunk) / 2) +
49800                   ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
49801 
49802       // The  low half of the 128-bit result must choose from A.
49803       // The high half of the 128-bit result must choose from B,
49804       // unless B is undef. In that case, we are always choosing from A.
49805       if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
49806         Index += NumEltsPer64BitChunk;
49807       PostShuffleMask[i + j] = Index;
49808     }
49809   }
49810 
49811   SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
49812   SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
49813 
49814   bool IsIdentityPostShuffle =
49815       isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
49816   if (IsIdentityPostShuffle)
49817     PostShuffleMask.clear();
49818 
49819   // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
49820   if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
49821       isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
49822     return false;
49823 
49824   // If the source nodes are already used in HorizOps then always accept this.
49825   // Shuffle folding should merge these back together.
49826   bool FoundHorizLHS = llvm::any_of(NewLHS->uses(), [&](SDNode *User) {
49827     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
49828   });
49829   bool FoundHorizRHS = llvm::any_of(NewRHS->uses(), [&](SDNode *User) {
49830     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
49831   });
49832   bool ForceHorizOp = FoundHorizLHS && FoundHorizRHS;
49833 
49834   // Assume a SingleSource HOP if we only shuffle one input and don't need to
49835   // shuffle the result.
49836   if (!ForceHorizOp &&
49837       !shouldUseHorizontalOp(NewLHS == NewRHS &&
49838                                  (NumShuffles < 2 || !IsIdentityPostShuffle),
49839                              DAG, Subtarget))
49840     return false;
49841 
49842   LHS = DAG.getBitcast(VT, NewLHS);
49843   RHS = DAG.getBitcast(VT, NewRHS);
49844   return true;
49845 }
49846 
49847 // Try to synthesize horizontal (f)hadd/hsub from (f)adds/subs of shuffles.
49848 static SDValue combineToHorizontalAddSub(SDNode *N, SelectionDAG &DAG,
49849                                          const X86Subtarget &Subtarget) {
49850   EVT VT = N->getValueType(0);
49851   unsigned Opcode = N->getOpcode();
49852   bool IsAdd = (Opcode == ISD::FADD) || (Opcode == ISD::ADD);
49853   SmallVector<int, 8> PostShuffleMask;
49854 
49855   switch (Opcode) {
49856   case ISD::FADD:
49857   case ISD::FSUB:
49858     if ((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
49859         (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
49860       SDValue LHS = N->getOperand(0);
49861       SDValue RHS = N->getOperand(1);
49862       auto HorizOpcode = IsAdd ? X86ISD::FHADD : X86ISD::FHSUB;
49863       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
49864                             PostShuffleMask)) {
49865         SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
49866         if (!PostShuffleMask.empty())
49867           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
49868                                             DAG.getUNDEF(VT), PostShuffleMask);
49869         return HorizBinOp;
49870       }
49871     }
49872     break;
49873   case ISD::ADD:
49874   case ISD::SUB:
49875     if (Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
49876                                  VT == MVT::v16i16 || VT == MVT::v8i32)) {
49877       SDValue LHS = N->getOperand(0);
49878       SDValue RHS = N->getOperand(1);
49879       auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
49880       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
49881                             PostShuffleMask)) {
49882         auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
49883                                         ArrayRef<SDValue> Ops) {
49884           return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
49885         };
49886         SDValue HorizBinOp = SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
49887                                               {LHS, RHS}, HOpBuilder);
49888         if (!PostShuffleMask.empty())
49889           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
49890                                             DAG.getUNDEF(VT), PostShuffleMask);
49891         return HorizBinOp;
49892       }
49893     }
49894     break;
49895   }
49896 
49897   return SDValue();
49898 }
49899 
49900 //  Try to combine the following nodes
49901 //  t29: i64 = X86ISD::Wrapper TargetConstantPool:i64
49902 //    <i32 -2147483648[float -0.000000e+00]> 0
49903 //  t27: v16i32[v16f32],ch = X86ISD::VBROADCAST_LOAD
49904 //    <(load 4 from constant-pool)> t0, t29
49905 //  [t30: v16i32 = bitcast t27]
49906 //  t6: v16i32 = xor t7, t27[t30]
49907 //  t11: v16f32 = bitcast t6
49908 //  t21: v16f32 = X86ISD::VFMULC[X86ISD::VCFMULC] t11, t8
49909 //  into X86ISD::VFCMULC[X86ISD::VFMULC] if possible:
49910 //  t22: v16f32 = bitcast t7
49911 //  t23: v16f32 = X86ISD::VFCMULC[X86ISD::VFMULC] t8, t22
49912 //  t24: v32f16 = bitcast t23
49913 static SDValue combineFMulcFCMulc(SDNode *N, SelectionDAG &DAG,
49914                                   const X86Subtarget &Subtarget) {
49915   EVT VT = N->getValueType(0);
49916   SDValue LHS = N->getOperand(0);
49917   SDValue RHS = N->getOperand(1);
49918   int CombineOpcode =
49919       N->getOpcode() == X86ISD::VFCMULC ? X86ISD::VFMULC : X86ISD::VFCMULC;
49920   auto isConjugationConstant = [](const Constant *c) {
49921     if (const auto *CI = dyn_cast<ConstantInt>(c)) {
49922       APInt ConjugationInt32 = APInt(32, 0x80000000, true);
49923       APInt ConjugationInt64 = APInt(64, 0x8000000080000000ULL, true);
49924       switch (CI->getBitWidth()) {
49925       case 16:
49926         return false;
49927       case 32:
49928         return CI->getValue() == ConjugationInt32;
49929       case 64:
49930         return CI->getValue() == ConjugationInt64;
49931       default:
49932         llvm_unreachable("Unexpected bit width");
49933       }
49934     }
49935     if (const auto *CF = dyn_cast<ConstantFP>(c))
49936       return CF->isNegativeZeroValue();
49937     return false;
49938   };
49939   auto combineConjugation = [&](SDValue &r) {
49940     if (LHS->getOpcode() == ISD::BITCAST && RHS.hasOneUse()) {
49941       SDValue XOR = LHS.getOperand(0);
49942       if (XOR->getOpcode() == ISD::XOR && XOR.hasOneUse()) {
49943         SDValue XORRHS = XOR.getOperand(1);
49944         if (XORRHS.getOpcode() == ISD::BITCAST && XORRHS.hasOneUse())
49945           XORRHS = XORRHS.getOperand(0);
49946         if (XORRHS.getOpcode() == X86ISD::VBROADCAST_LOAD &&
49947             XORRHS.getOperand(1).getNumOperands()) {
49948           ConstantPoolSDNode *CP =
49949               dyn_cast<ConstantPoolSDNode>(XORRHS.getOperand(1).getOperand(0));
49950           if (CP && isConjugationConstant(CP->getConstVal())) {
49951             SelectionDAG::FlagInserter FlagsInserter(DAG, N);
49952             SDValue I2F = DAG.getBitcast(VT, LHS.getOperand(0).getOperand(0));
49953             SDValue FCMulC = DAG.getNode(CombineOpcode, SDLoc(N), VT, RHS, I2F);
49954             r = DAG.getBitcast(VT, FCMulC);
49955             return true;
49956           }
49957         }
49958       }
49959     }
49960     return false;
49961   };
49962   SDValue Res;
49963   if (combineConjugation(Res))
49964     return Res;
49965   std::swap(LHS, RHS);
49966   if (combineConjugation(Res))
49967     return Res;
49968   return Res;
49969 }
49970 
49971 //  Try to combine the following nodes:
49972 //  FADD(A, FMA(B, C, 0)) and FADD(A, FMUL(B, C)) to FMA(B, C, A)
49973 static SDValue combineFaddCFmul(SDNode *N, SelectionDAG &DAG,
49974                                 const X86Subtarget &Subtarget) {
49975   auto AllowContract = [&DAG](const SDNodeFlags &Flags) {
49976     return DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
49977            Flags.hasAllowContract();
49978   };
49979 
49980   auto HasNoSignedZero = [&DAG](const SDNodeFlags &Flags) {
49981     return DAG.getTarget().Options.NoSignedZerosFPMath ||
49982            Flags.hasNoSignedZeros();
49983   };
49984   auto IsVectorAllNegativeZero = [](const SDNode *N) {
49985     if (N->getOpcode() != X86ISD::VBROADCAST_LOAD)
49986       return false;
49987     assert(N->getSimpleValueType(0).getScalarType() == MVT::f32 &&
49988            "Unexpected vector type!");
49989     if (ConstantPoolSDNode *CP =
49990             dyn_cast<ConstantPoolSDNode>(N->getOperand(1)->getOperand(0))) {
49991       APInt AI = APInt(32, 0x80008000, true);
49992       if (const auto *CI = dyn_cast<ConstantInt>(CP->getConstVal()))
49993         return CI->getValue() == AI;
49994       if (const auto *CF = dyn_cast<ConstantFP>(CP->getConstVal()))
49995         return CF->getValue() == APFloat(APFloat::IEEEsingle(), AI);
49996     }
49997     return false;
49998   };
49999 
50000   if (N->getOpcode() != ISD::FADD || !Subtarget.hasFP16() ||
50001       !AllowContract(N->getFlags()))
50002     return SDValue();
50003 
50004   EVT VT = N->getValueType(0);
50005   if (VT != MVT::v8f16 && VT != MVT::v16f16 && VT != MVT::v32f16)
50006     return SDValue();
50007 
50008   SDValue LHS = N->getOperand(0);
50009   SDValue RHS = N->getOperand(1);
50010   bool IsConj;
50011   SDValue FAddOp1, MulOp0, MulOp1;
50012   auto GetCFmulFrom = [&MulOp0, &MulOp1, &IsConj, &AllowContract,
50013                        &IsVectorAllNegativeZero,
50014                        &HasNoSignedZero](SDValue N) -> bool {
50015     if (!N.hasOneUse() || N.getOpcode() != ISD::BITCAST)
50016       return false;
50017     SDValue Op0 = N.getOperand(0);
50018     unsigned Opcode = Op0.getOpcode();
50019     if (Op0.hasOneUse() && AllowContract(Op0->getFlags())) {
50020       if ((Opcode == X86ISD::VFMULC || Opcode == X86ISD::VFCMULC)) {
50021         MulOp0 = Op0.getOperand(0);
50022         MulOp1 = Op0.getOperand(1);
50023         IsConj = Opcode == X86ISD::VFCMULC;
50024         return true;
50025       }
50026       if ((Opcode == X86ISD::VFMADDC || Opcode == X86ISD::VFCMADDC) &&
50027           ((ISD::isBuildVectorAllZeros(Op0->getOperand(2).getNode()) &&
50028             HasNoSignedZero(Op0->getFlags())) ||
50029            IsVectorAllNegativeZero(Op0->getOperand(2).getNode()))) {
50030         MulOp0 = Op0.getOperand(0);
50031         MulOp1 = Op0.getOperand(1);
50032         IsConj = Opcode == X86ISD::VFCMADDC;
50033         return true;
50034       }
50035     }
50036     return false;
50037   };
50038 
50039   if (GetCFmulFrom(LHS))
50040     FAddOp1 = RHS;
50041   else if (GetCFmulFrom(RHS))
50042     FAddOp1 = LHS;
50043   else
50044     return SDValue();
50045 
50046   MVT CVT = MVT::getVectorVT(MVT::f32, VT.getVectorNumElements() / 2);
50047   FAddOp1 = DAG.getBitcast(CVT, FAddOp1);
50048   unsigned NewOp = IsConj ? X86ISD::VFCMADDC : X86ISD::VFMADDC;
50049   // FIXME: How do we handle when fast math flags of FADD are different from
50050   // CFMUL's?
50051   SDValue CFmul =
50052       DAG.getNode(NewOp, SDLoc(N), CVT, MulOp0, MulOp1, FAddOp1, N->getFlags());
50053   return DAG.getBitcast(VT, CFmul);
50054 }
50055 
50056 /// Do target-specific dag combines on floating-point adds/subs.
50057 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
50058                                const X86Subtarget &Subtarget) {
50059   if (SDValue HOp = combineToHorizontalAddSub(N, DAG, Subtarget))
50060     return HOp;
50061 
50062   if (SDValue COp = combineFaddCFmul(N, DAG, Subtarget))
50063     return COp;
50064 
50065   return SDValue();
50066 }
50067 
50068 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
50069 /// the codegen.
50070 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
50071 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
50072 ///       anything that is guaranteed to be transformed by DAGCombiner.
50073 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
50074                                           const X86Subtarget &Subtarget,
50075                                           const SDLoc &DL) {
50076   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
50077   SDValue Src = N->getOperand(0);
50078   unsigned SrcOpcode = Src.getOpcode();
50079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50080 
50081   EVT VT = N->getValueType(0);
50082   EVT SrcVT = Src.getValueType();
50083 
50084   auto IsFreeTruncation = [VT](SDValue Op) {
50085     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
50086 
50087     // See if this has been extended from a smaller/equal size to
50088     // the truncation size, allowing a truncation to combine with the extend.
50089     unsigned Opcode = Op.getOpcode();
50090     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
50091          Opcode == ISD::ZERO_EXTEND) &&
50092         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
50093       return true;
50094 
50095     // See if this is a single use constant which can be constant folded.
50096     // NOTE: We don't peek throught bitcasts here because there is currently
50097     // no support for constant folding truncate+bitcast+vector_of_constants. So
50098     // we'll just send up with a truncate on both operands which will
50099     // get turned back into (truncate (binop)) causing an infinite loop.
50100     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
50101   };
50102 
50103   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
50104     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
50105     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
50106     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
50107   };
50108 
50109   // Don't combine if the operation has other uses.
50110   if (!Src.hasOneUse())
50111     return SDValue();
50112 
50113   // Only support vector truncation for now.
50114   // TODO: i64 scalar math would benefit as well.
50115   if (!VT.isVector())
50116     return SDValue();
50117 
50118   // In most cases its only worth pre-truncating if we're only facing the cost
50119   // of one truncation.
50120   // i.e. if one of the inputs will constant fold or the input is repeated.
50121   switch (SrcOpcode) {
50122   case ISD::MUL:
50123     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
50124     // better to truncate if we have the chance.
50125     if (SrcVT.getScalarType() == MVT::i64 &&
50126         TLI.isOperationLegal(SrcOpcode, VT) &&
50127         !TLI.isOperationLegal(SrcOpcode, SrcVT))
50128       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
50129     LLVM_FALLTHROUGH;
50130   case ISD::AND:
50131   case ISD::XOR:
50132   case ISD::OR:
50133   case ISD::ADD:
50134   case ISD::SUB: {
50135     SDValue Op0 = Src.getOperand(0);
50136     SDValue Op1 = Src.getOperand(1);
50137     if (TLI.isOperationLegal(SrcOpcode, VT) &&
50138         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
50139       return TruncateArithmetic(Op0, Op1);
50140     break;
50141   }
50142   }
50143 
50144   return SDValue();
50145 }
50146 
50147 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
50148 /// e.g. trunc <8 x i32> X to <8 x i16> -->
50149 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
50150 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
50151 static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
50152                                                  const X86Subtarget &Subtarget,
50153                                                  SelectionDAG &DAG) {
50154   SDValue In = N->getOperand(0);
50155   EVT InVT = In.getValueType();
50156   EVT OutVT = N->getValueType(0);
50157 
50158   APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
50159                                     OutVT.getScalarSizeInBits());
50160   In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
50161   return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
50162 }
50163 
50164 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
50165 static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
50166                                                  const X86Subtarget &Subtarget,
50167                                                  SelectionDAG &DAG) {
50168   SDValue In = N->getOperand(0);
50169   EVT InVT = In.getValueType();
50170   EVT OutVT = N->getValueType(0);
50171   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
50172                    DAG.getValueType(OutVT));
50173   return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
50174 }
50175 
50176 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
50177 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
50178 /// legalization the truncation will be translated into a BUILD_VECTOR with each
50179 /// element that is extracted from a vector and then truncated, and it is
50180 /// difficult to do this optimization based on them.
50181 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
50182                                        const X86Subtarget &Subtarget) {
50183   EVT OutVT = N->getValueType(0);
50184   if (!OutVT.isVector())
50185     return SDValue();
50186 
50187   SDValue In = N->getOperand(0);
50188   if (!In.getValueType().isSimple())
50189     return SDValue();
50190 
50191   EVT InVT = In.getValueType();
50192   unsigned NumElems = OutVT.getVectorNumElements();
50193 
50194   // AVX512 provides fast truncate ops.
50195   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
50196     return SDValue();
50197 
50198   EVT OutSVT = OutVT.getVectorElementType();
50199   EVT InSVT = InVT.getVectorElementType();
50200   if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) &&
50201         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
50202         NumElems >= 8))
50203     return SDValue();
50204 
50205   // SSSE3's pshufb results in less instructions in the cases below.
50206   if (Subtarget.hasSSSE3() && NumElems == 8) {
50207     if (InSVT == MVT::i16)
50208       return SDValue();
50209     if (InSVT == MVT::i32 &&
50210         (OutSVT == MVT::i8 || !Subtarget.hasSSE41() || Subtarget.hasInt256()))
50211       return SDValue();
50212   }
50213 
50214   SDLoc DL(N);
50215   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
50216   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
50217   // truncate 2 x v4i32 to v8i16.
50218   if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
50219     return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
50220   if (InSVT == MVT::i32)
50221     return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
50222 
50223   return SDValue();
50224 }
50225 
50226 /// This function transforms vector truncation of 'extended sign-bits' or
50227 /// 'extended zero-bits' values.
50228 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
50229 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
50230                                                SelectionDAG &DAG,
50231                                                const X86Subtarget &Subtarget) {
50232   // Requires SSE2.
50233   if (!Subtarget.hasSSE2())
50234     return SDValue();
50235 
50236   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
50237     return SDValue();
50238 
50239   SDValue In = N->getOperand(0);
50240   if (!In.getValueType().isSimple())
50241     return SDValue();
50242 
50243   MVT VT = N->getValueType(0).getSimpleVT();
50244   MVT SVT = VT.getScalarType();
50245 
50246   MVT InVT = In.getValueType().getSimpleVT();
50247   MVT InSVT = InVT.getScalarType();
50248 
50249   // Check we have a truncation suited for PACKSS/PACKUS.
50250   if (!isPowerOf2_32(VT.getVectorNumElements()))
50251     return SDValue();
50252   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
50253     return SDValue();
50254   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
50255     return SDValue();
50256 
50257   // Truncation to sub-128bit vXi32 can be better handled with shuffles.
50258   if (SVT == MVT::i32 && VT.getSizeInBits() < 128)
50259     return SDValue();
50260 
50261   // AVX512 has fast truncate, but if the input is already going to be split,
50262   // there's no harm in trying pack.
50263   if (Subtarget.hasAVX512() &&
50264       !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
50265         InVT.is512BitVector())) {
50266     // PACK should still be worth it for 128-bit vectors if the sources were
50267     // originally concatenated from subvectors.
50268     SmallVector<SDValue> ConcatOps;
50269     if (VT.getSizeInBits() > 128 ||
50270         !collectConcatOps(In.getNode(), ConcatOps, DAG))
50271       return SDValue();
50272   }
50273 
50274   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
50275   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
50276 
50277   // Use PACKUS if the input has zero-bits that extend all the way to the
50278   // packed/truncated value. e.g. masks, zext_in_reg, etc.
50279   KnownBits Known = DAG.computeKnownBits(In);
50280   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
50281   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
50282     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
50283 
50284   // Use PACKSS if the input has sign-bits that extend all the way to the
50285   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
50286   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
50287 
50288   // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
50289   // a sign splat. ComputeNumSignBits struggles to see through BITCASTs later
50290   // on and combines/simplifications can't then use it.
50291   if (SVT == MVT::i32 && NumSignBits != InSVT.getSizeInBits())
50292     return SDValue();
50293 
50294   unsigned MinSignBits = InSVT.getSizeInBits() - NumPackedSignBits;
50295   if (NumSignBits > MinSignBits)
50296     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
50297 
50298   // If we have a srl that only generates signbits that we will discard in
50299   // the truncation then we can use PACKSS by converting the srl to a sra.
50300   // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
50301   if (In.getOpcode() == ISD::SRL && N->isOnlyUserOf(In.getNode()))
50302     if (const APInt *ShAmt = DAG.getValidShiftAmountConstant(
50303             In, APInt::getAllOnes(VT.getVectorNumElements()))) {
50304       if (*ShAmt == MinSignBits) {
50305         SDValue NewIn = DAG.getNode(ISD::SRA, DL, InVT, In->ops());
50306         return truncateVectorWithPACK(X86ISD::PACKSS, VT, NewIn, DL, DAG,
50307                                       Subtarget);
50308       }
50309     }
50310 
50311   return SDValue();
50312 }
50313 
50314 // Try to form a MULHU or MULHS node by looking for
50315 // (trunc (srl (mul ext, ext), 16))
50316 // TODO: This is X86 specific because we want to be able to handle wide types
50317 // before type legalization. But we can only do it if the vector will be
50318 // legalized via widening/splitting. Type legalization can't handle promotion
50319 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
50320 // combiner.
50321 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
50322                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
50323   // First instruction should be a right shift of a multiply.
50324   if (Src.getOpcode() != ISD::SRL ||
50325       Src.getOperand(0).getOpcode() != ISD::MUL)
50326     return SDValue();
50327 
50328   if (!Subtarget.hasSSE2())
50329     return SDValue();
50330 
50331   // Only handle vXi16 types that are at least 128-bits unless they will be
50332   // widened.
50333   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
50334     return SDValue();
50335 
50336   // Input type should be at least vXi32.
50337   EVT InVT = Src.getValueType();
50338   if (InVT.getVectorElementType().getSizeInBits() < 32)
50339     return SDValue();
50340 
50341   // Need a shift by 16.
50342   APInt ShiftAmt;
50343   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
50344       ShiftAmt != 16)
50345     return SDValue();
50346 
50347   SDValue LHS = Src.getOperand(0).getOperand(0);
50348   SDValue RHS = Src.getOperand(0).getOperand(1);
50349 
50350   // Count leading sign/zero bits on both inputs - if there are enough then
50351   // truncation back to vXi16 will be cheap - either as a pack/shuffle
50352   // sequence or using AVX512 truncations. If the inputs are sext/zext then the
50353   // truncations may actually be free by peeking through to the ext source.
50354   auto IsSext = [&DAG](SDValue V) {
50355     return DAG.ComputeMaxSignificantBits(V) <= 16;
50356   };
50357   auto IsZext = [&DAG](SDValue V) {
50358     return DAG.computeKnownBits(V).countMaxActiveBits() <= 16;
50359   };
50360 
50361   bool IsSigned = IsSext(LHS) && IsSext(RHS);
50362   bool IsUnsigned = IsZext(LHS) && IsZext(RHS);
50363   if (!IsSigned && !IsUnsigned)
50364     return SDValue();
50365 
50366   // Check if both inputs are extensions, which will be removed by truncation.
50367   bool IsTruncateFree = (LHS.getOpcode() == ISD::SIGN_EXTEND ||
50368                          LHS.getOpcode() == ISD::ZERO_EXTEND) &&
50369                         (RHS.getOpcode() == ISD::SIGN_EXTEND ||
50370                          RHS.getOpcode() == ISD::ZERO_EXTEND) &&
50371                         LHS.getOperand(0).getScalarValueSizeInBits() <= 16 &&
50372                         RHS.getOperand(0).getScalarValueSizeInBits() <= 16;
50373 
50374   // For AVX2+ targets, with the upper bits known zero, we can perform MULHU on
50375   // the (bitcasted) inputs directly, and then cheaply pack/truncate the result
50376   // (upper elts will be zero). Don't attempt this with just AVX512F as MULHU
50377   // will have to split anyway.
50378   unsigned InSizeInBits = InVT.getSizeInBits();
50379   if (IsUnsigned && !IsTruncateFree && Subtarget.hasInt256() &&
50380       !(Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.is256BitVector()) &&
50381       (InSizeInBits % 16) == 0) {
50382     EVT BCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
50383                                 InVT.getSizeInBits() / 16);
50384     SDValue Res = DAG.getNode(ISD::MULHU, DL, BCVT, DAG.getBitcast(BCVT, LHS),
50385                               DAG.getBitcast(BCVT, RHS));
50386     return DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getBitcast(InVT, Res));
50387   }
50388 
50389   // Truncate back to source type.
50390   LHS = DAG.getNode(ISD::TRUNCATE, DL, VT, LHS);
50391   RHS = DAG.getNode(ISD::TRUNCATE, DL, VT, RHS);
50392 
50393   unsigned Opc = IsSigned ? ISD::MULHS : ISD::MULHU;
50394   return DAG.getNode(Opc, DL, VT, LHS, RHS);
50395 }
50396 
50397 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
50398 // from one vector with signed bytes from another vector, adds together
50399 // adjacent pairs of 16-bit products, and saturates the result before
50400 // truncating to 16-bits.
50401 //
50402 // Which looks something like this:
50403 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
50404 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
50405 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
50406                                const X86Subtarget &Subtarget,
50407                                const SDLoc &DL) {
50408   if (!VT.isVector() || !Subtarget.hasSSSE3())
50409     return SDValue();
50410 
50411   unsigned NumElems = VT.getVectorNumElements();
50412   EVT ScalarVT = VT.getVectorElementType();
50413   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
50414     return SDValue();
50415 
50416   SDValue SSatVal = detectSSatPattern(In, VT);
50417   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
50418     return SDValue();
50419 
50420   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
50421   // of multiplies from even/odd elements.
50422   SDValue N0 = SSatVal.getOperand(0);
50423   SDValue N1 = SSatVal.getOperand(1);
50424 
50425   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
50426     return SDValue();
50427 
50428   SDValue N00 = N0.getOperand(0);
50429   SDValue N01 = N0.getOperand(1);
50430   SDValue N10 = N1.getOperand(0);
50431   SDValue N11 = N1.getOperand(1);
50432 
50433   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
50434   // Canonicalize zero_extend to LHS.
50435   if (N01.getOpcode() == ISD::ZERO_EXTEND)
50436     std::swap(N00, N01);
50437   if (N11.getOpcode() == ISD::ZERO_EXTEND)
50438     std::swap(N10, N11);
50439 
50440   // Ensure we have a zero_extend and a sign_extend.
50441   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
50442       N01.getOpcode() != ISD::SIGN_EXTEND ||
50443       N10.getOpcode() != ISD::ZERO_EXTEND ||
50444       N11.getOpcode() != ISD::SIGN_EXTEND)
50445     return SDValue();
50446 
50447   // Peek through the extends.
50448   N00 = N00.getOperand(0);
50449   N01 = N01.getOperand(0);
50450   N10 = N10.getOperand(0);
50451   N11 = N11.getOperand(0);
50452 
50453   // Ensure the extend is from vXi8.
50454   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
50455       N01.getValueType().getVectorElementType() != MVT::i8 ||
50456       N10.getValueType().getVectorElementType() != MVT::i8 ||
50457       N11.getValueType().getVectorElementType() != MVT::i8)
50458     return SDValue();
50459 
50460   // All inputs should be build_vectors.
50461   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
50462       N01.getOpcode() != ISD::BUILD_VECTOR ||
50463       N10.getOpcode() != ISD::BUILD_VECTOR ||
50464       N11.getOpcode() != ISD::BUILD_VECTOR)
50465     return SDValue();
50466 
50467   // N00/N10 are zero extended. N01/N11 are sign extended.
50468 
50469   // For each element, we need to ensure we have an odd element from one vector
50470   // multiplied by the odd element of another vector and the even element from
50471   // one of the same vectors being multiplied by the even element from the
50472   // other vector. So we need to make sure for each element i, this operator
50473   // is being performed:
50474   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
50475   SDValue ZExtIn, SExtIn;
50476   for (unsigned i = 0; i != NumElems; ++i) {
50477     SDValue N00Elt = N00.getOperand(i);
50478     SDValue N01Elt = N01.getOperand(i);
50479     SDValue N10Elt = N10.getOperand(i);
50480     SDValue N11Elt = N11.getOperand(i);
50481     // TODO: Be more tolerant to undefs.
50482     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
50483         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
50484         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
50485         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
50486       return SDValue();
50487     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
50488     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
50489     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
50490     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
50491     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
50492       return SDValue();
50493     unsigned IdxN00 = ConstN00Elt->getZExtValue();
50494     unsigned IdxN01 = ConstN01Elt->getZExtValue();
50495     unsigned IdxN10 = ConstN10Elt->getZExtValue();
50496     unsigned IdxN11 = ConstN11Elt->getZExtValue();
50497     // Add is commutative so indices can be reordered.
50498     if (IdxN00 > IdxN10) {
50499       std::swap(IdxN00, IdxN10);
50500       std::swap(IdxN01, IdxN11);
50501     }
50502     // N0 indices be the even element. N1 indices must be the next odd element.
50503     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
50504         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
50505       return SDValue();
50506     SDValue N00In = N00Elt.getOperand(0);
50507     SDValue N01In = N01Elt.getOperand(0);
50508     SDValue N10In = N10Elt.getOperand(0);
50509     SDValue N11In = N11Elt.getOperand(0);
50510     // First time we find an input capture it.
50511     if (!ZExtIn) {
50512       ZExtIn = N00In;
50513       SExtIn = N01In;
50514     }
50515     if (ZExtIn != N00In || SExtIn != N01In ||
50516         ZExtIn != N10In || SExtIn != N11In)
50517       return SDValue();
50518   }
50519 
50520   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
50521                          ArrayRef<SDValue> Ops) {
50522     // Shrink by adding truncate nodes and let DAGCombine fold with the
50523     // sources.
50524     EVT InVT = Ops[0].getValueType();
50525     assert(InVT.getScalarType() == MVT::i8 &&
50526            "Unexpected scalar element type");
50527     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
50528     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
50529                                  InVT.getVectorNumElements() / 2);
50530     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
50531   };
50532   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
50533                           PMADDBuilder);
50534 }
50535 
50536 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
50537                                const X86Subtarget &Subtarget) {
50538   EVT VT = N->getValueType(0);
50539   SDValue Src = N->getOperand(0);
50540   SDLoc DL(N);
50541 
50542   // Attempt to pre-truncate inputs to arithmetic ops instead.
50543   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
50544     return V;
50545 
50546   // Try to detect AVG pattern first.
50547   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
50548     return Avg;
50549 
50550   // Try to detect PMADD
50551   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
50552     return PMAdd;
50553 
50554   // Try to combine truncation with signed/unsigned saturation.
50555   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
50556     return Val;
50557 
50558   // Try to combine PMULHUW/PMULHW for vXi16.
50559   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
50560     return V;
50561 
50562   // The bitcast source is a direct mmx result.
50563   // Detect bitcasts between i32 to x86mmx
50564   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
50565     SDValue BCSrc = Src.getOperand(0);
50566     if (BCSrc.getValueType() == MVT::x86mmx)
50567       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
50568   }
50569 
50570   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
50571   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
50572     return V;
50573 
50574   return combineVectorTruncation(N, DAG, Subtarget);
50575 }
50576 
50577 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
50578                              TargetLowering::DAGCombinerInfo &DCI) {
50579   EVT VT = N->getValueType(0);
50580   SDValue In = N->getOperand(0);
50581   SDLoc DL(N);
50582 
50583   if (SDValue SSatVal = detectSSatPattern(In, VT))
50584     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
50585   if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL))
50586     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
50587 
50588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50589   APInt DemandedMask(APInt::getAllOnes(VT.getScalarSizeInBits()));
50590   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
50591     return SDValue(N, 0);
50592 
50593   return SDValue();
50594 }
50595 
50596 /// Returns the negated value if the node \p N flips sign of FP value.
50597 ///
50598 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
50599 /// or FSUB(0, x)
50600 /// AVX512F does not have FXOR, so FNEG is lowered as
50601 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
50602 /// In this case we go though all bitcasts.
50603 /// This also recognizes splat of a negated value and returns the splat of that
50604 /// value.
50605 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
50606   if (N->getOpcode() == ISD::FNEG)
50607     return N->getOperand(0);
50608 
50609   // Don't recurse exponentially.
50610   if (Depth > SelectionDAG::MaxRecursionDepth)
50611     return SDValue();
50612 
50613   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
50614 
50615   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
50616   EVT VT = Op->getValueType(0);
50617 
50618   // Make sure the element size doesn't change.
50619   if (VT.getScalarSizeInBits() != ScalarSize)
50620     return SDValue();
50621 
50622   unsigned Opc = Op.getOpcode();
50623   switch (Opc) {
50624   case ISD::VECTOR_SHUFFLE: {
50625     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
50626     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
50627     if (!Op.getOperand(1).isUndef())
50628       return SDValue();
50629     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
50630       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
50631         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
50632                                     cast<ShuffleVectorSDNode>(Op)->getMask());
50633     break;
50634   }
50635   case ISD::INSERT_VECTOR_ELT: {
50636     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
50637     // -V, INDEX).
50638     SDValue InsVector = Op.getOperand(0);
50639     SDValue InsVal = Op.getOperand(1);
50640     if (!InsVector.isUndef())
50641       return SDValue();
50642     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
50643       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
50644         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
50645                            NegInsVal, Op.getOperand(2));
50646     break;
50647   }
50648   case ISD::FSUB:
50649   case ISD::XOR:
50650   case X86ISD::FXOR: {
50651     SDValue Op1 = Op.getOperand(1);
50652     SDValue Op0 = Op.getOperand(0);
50653 
50654     // For XOR and FXOR, we want to check if constant
50655     // bits of Op1 are sign bit masks. For FSUB, we
50656     // have to check if constant bits of Op0 are sign
50657     // bit masks and hence we swap the operands.
50658     if (Opc == ISD::FSUB)
50659       std::swap(Op0, Op1);
50660 
50661     APInt UndefElts;
50662     SmallVector<APInt, 16> EltBits;
50663     // Extract constant bits and see if they are all
50664     // sign bit masks. Ignore the undef elements.
50665     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
50666                                       /* AllowWholeUndefs */ true,
50667                                       /* AllowPartialUndefs */ false)) {
50668       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
50669         if (!UndefElts[I] && !EltBits[I].isSignMask())
50670           return SDValue();
50671 
50672       // Only allow bitcast from correctly-sized constant.
50673       Op0 = peekThroughBitcasts(Op0);
50674       if (Op0.getScalarValueSizeInBits() == ScalarSize)
50675         return Op0;
50676     }
50677     break;
50678   } // case
50679   } // switch
50680 
50681   return SDValue();
50682 }
50683 
50684 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
50685                                 bool NegRes) {
50686   if (NegMul) {
50687     switch (Opcode) {
50688     default: llvm_unreachable("Unexpected opcode");
50689     case ISD::FMA:              Opcode = X86ISD::FNMADD;        break;
50690     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FNMADD; break;
50691     case X86ISD::FMADD_RND:     Opcode = X86ISD::FNMADD_RND;    break;
50692     case X86ISD::FMSUB:         Opcode = X86ISD::FNMSUB;        break;
50693     case X86ISD::STRICT_FMSUB:  Opcode = X86ISD::STRICT_FNMSUB; break;
50694     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FNMSUB_RND;    break;
50695     case X86ISD::FNMADD:        Opcode = ISD::FMA;              break;
50696     case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA;       break;
50697     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FMADD_RND;     break;
50698     case X86ISD::FNMSUB:        Opcode = X86ISD::FMSUB;         break;
50699     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB;  break;
50700     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FMSUB_RND;     break;
50701     }
50702   }
50703 
50704   if (NegAcc) {
50705     switch (Opcode) {
50706     default: llvm_unreachable("Unexpected opcode");
50707     case ISD::FMA:              Opcode = X86ISD::FMSUB;         break;
50708     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FMSUB;  break;
50709     case X86ISD::FMADD_RND:     Opcode = X86ISD::FMSUB_RND;     break;
50710     case X86ISD::FMSUB:         Opcode = ISD::FMA;              break;
50711     case X86ISD::STRICT_FMSUB:  Opcode = ISD::STRICT_FMA;       break;
50712     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FMADD_RND;     break;
50713     case X86ISD::FNMADD:        Opcode = X86ISD::FNMSUB;        break;
50714     case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
50715     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FNMSUB_RND;    break;
50716     case X86ISD::FNMSUB:        Opcode = X86ISD::FNMADD;        break;
50717     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
50718     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FNMADD_RND;    break;
50719     case X86ISD::FMADDSUB:      Opcode = X86ISD::FMSUBADD;      break;
50720     case X86ISD::FMADDSUB_RND:  Opcode = X86ISD::FMSUBADD_RND;  break;
50721     case X86ISD::FMSUBADD:      Opcode = X86ISD::FMADDSUB;      break;
50722     case X86ISD::FMSUBADD_RND:  Opcode = X86ISD::FMADDSUB_RND;  break;
50723     }
50724   }
50725 
50726   if (NegRes) {
50727     switch (Opcode) {
50728     // For accuracy reason, we never combine fneg and fma under strict FP.
50729     default: llvm_unreachable("Unexpected opcode");
50730     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
50731     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
50732     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
50733     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
50734     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
50735     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
50736     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
50737     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
50738     }
50739   }
50740 
50741   return Opcode;
50742 }
50743 
50744 /// Do target-specific dag combines on floating point negations.
50745 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
50746                            TargetLowering::DAGCombinerInfo &DCI,
50747                            const X86Subtarget &Subtarget) {
50748   EVT OrigVT = N->getValueType(0);
50749   SDValue Arg = isFNEG(DAG, N);
50750   if (!Arg)
50751     return SDValue();
50752 
50753   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50754   EVT VT = Arg.getValueType();
50755   EVT SVT = VT.getScalarType();
50756   SDLoc DL(N);
50757 
50758   // Let legalize expand this if it isn't a legal type yet.
50759   if (!TLI.isTypeLegal(VT))
50760     return SDValue();
50761 
50762   // If we're negating a FMUL node on a target with FMA, then we can avoid the
50763   // use of a constant by performing (-0 - A*B) instead.
50764   // FIXME: Check rounding control flags as well once it becomes available.
50765   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
50766       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
50767     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
50768     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
50769                                   Arg.getOperand(1), Zero);
50770     return DAG.getBitcast(OrigVT, NewNode);
50771   }
50772 
50773   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
50774   bool LegalOperations = !DCI.isBeforeLegalizeOps();
50775   if (SDValue NegArg =
50776           TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
50777     return DAG.getBitcast(OrigVT, NegArg);
50778 
50779   return SDValue();
50780 }
50781 
50782 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
50783                                                 bool LegalOperations,
50784                                                 bool ForCodeSize,
50785                                                 NegatibleCost &Cost,
50786                                                 unsigned Depth) const {
50787   // fneg patterns are removable even if they have multiple uses.
50788   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
50789     Cost = NegatibleCost::Cheaper;
50790     return DAG.getBitcast(Op.getValueType(), Arg);
50791   }
50792 
50793   EVT VT = Op.getValueType();
50794   EVT SVT = VT.getScalarType();
50795   unsigned Opc = Op.getOpcode();
50796   SDNodeFlags Flags = Op.getNode()->getFlags();
50797   switch (Opc) {
50798   case ISD::FMA:
50799   case X86ISD::FMSUB:
50800   case X86ISD::FNMADD:
50801   case X86ISD::FNMSUB:
50802   case X86ISD::FMADD_RND:
50803   case X86ISD::FMSUB_RND:
50804   case X86ISD::FNMADD_RND:
50805   case X86ISD::FNMSUB_RND: {
50806     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
50807         !(SVT == MVT::f32 || SVT == MVT::f64) ||
50808         !isOperationLegal(ISD::FMA, VT))
50809       break;
50810 
50811     // Don't fold (fneg (fma (fneg x), y, (fneg z))) to (fma x, y, z)
50812     // if it may have signed zeros.
50813     if (!Flags.hasNoSignedZeros())
50814       break;
50815 
50816     // This is always negatible for free but we might be able to remove some
50817     // extra operand negations as well.
50818     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
50819     for (int i = 0; i != 3; ++i)
50820       NewOps[i] = getCheaperNegatedExpression(
50821           Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
50822 
50823     bool NegA = !!NewOps[0];
50824     bool NegB = !!NewOps[1];
50825     bool NegC = !!NewOps[2];
50826     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
50827 
50828     Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
50829                                   : NegatibleCost::Neutral;
50830 
50831     // Fill in the non-negated ops with the original values.
50832     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
50833       if (!NewOps[i])
50834         NewOps[i] = Op.getOperand(i);
50835     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
50836   }
50837   case X86ISD::FRCP:
50838     if (SDValue NegOp0 =
50839             getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
50840                                  ForCodeSize, Cost, Depth + 1))
50841       return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
50842     break;
50843   }
50844 
50845   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
50846                                               ForCodeSize, Cost, Depth);
50847 }
50848 
50849 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
50850                                  const X86Subtarget &Subtarget) {
50851   MVT VT = N->getSimpleValueType(0);
50852   // If we have integer vector types available, use the integer opcodes.
50853   if (!VT.isVector() || !Subtarget.hasSSE2())
50854     return SDValue();
50855 
50856   SDLoc dl(N);
50857 
50858   unsigned IntBits = VT.getScalarSizeInBits();
50859   MVT IntSVT = MVT::getIntegerVT(IntBits);
50860   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
50861 
50862   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
50863   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
50864   unsigned IntOpcode;
50865   switch (N->getOpcode()) {
50866   default: llvm_unreachable("Unexpected FP logic op");
50867   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
50868   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
50869   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
50870   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
50871   }
50872   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
50873   return DAG.getBitcast(VT, IntOp);
50874 }
50875 
50876 
50877 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
50878 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
50879   if (N->getOpcode() != ISD::XOR)
50880     return SDValue();
50881 
50882   SDValue LHS = N->getOperand(0);
50883   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
50884     return SDValue();
50885 
50886   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
50887       X86::CondCode(LHS->getConstantOperandVal(0)));
50888   SDLoc DL(N);
50889   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
50890 }
50891 
50892 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
50893                           TargetLowering::DAGCombinerInfo &DCI,
50894                           const X86Subtarget &Subtarget) {
50895   SDValue N0 = N->getOperand(0);
50896   SDValue N1 = N->getOperand(1);
50897   EVT VT = N->getValueType(0);
50898 
50899   // If this is SSE1 only convert to FXOR to avoid scalarization.
50900   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
50901     return DAG.getBitcast(MVT::v4i32,
50902                           DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
50903                                       DAG.getBitcast(MVT::v4f32, N0),
50904                                       DAG.getBitcast(MVT::v4f32, N1)));
50905   }
50906 
50907   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
50908     return Cmp;
50909 
50910   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
50911     return R;
50912 
50913   if (SDValue R = combineBitOpWithShift(N, DAG))
50914     return R;
50915 
50916   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
50917     return FPLogic;
50918 
50919   if (DCI.isBeforeLegalizeOps())
50920     return SDValue();
50921 
50922   if (SDValue SetCC = foldXor1SetCC(N, DAG))
50923     return SetCC;
50924 
50925   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
50926     return RV;
50927 
50928   // Fold not(iX bitcast(vXi1)) -> (iX bitcast(not(vec))) for legal boolvecs.
50929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50930   if (llvm::isAllOnesConstant(N1) && N0.getOpcode() == ISD::BITCAST &&
50931       N0.getOperand(0).getValueType().isVector() &&
50932       N0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
50933       TLI.isTypeLegal(N0.getOperand(0).getValueType()) && N0.hasOneUse()) {
50934     return DAG.getBitcast(VT, DAG.getNOT(SDLoc(N), N0.getOperand(0),
50935                                          N0.getOperand(0).getValueType()));
50936   }
50937 
50938   // Handle AVX512 mask widening.
50939   // Fold not(insert_subvector(undef,sub)) -> insert_subvector(undef,not(sub))
50940   if (ISD::isBuildVectorAllOnes(N1.getNode()) && VT.isVector() &&
50941       VT.getVectorElementType() == MVT::i1 &&
50942       N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.getOperand(0).isUndef() &&
50943       TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
50944     return DAG.getNode(
50945         ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
50946         DAG.getNOT(SDLoc(N), N0.getOperand(1), N0.getOperand(1).getValueType()),
50947         N0.getOperand(2));
50948   }
50949 
50950   // Fold xor(zext(xor(x,c1)),c2) -> xor(zext(x),xor(zext(c1),c2))
50951   // Fold xor(truncate(xor(x,c1)),c2) -> xor(truncate(x),xor(truncate(c1),c2))
50952   // TODO: Under what circumstances could this be performed in DAGCombine?
50953   if ((N0.getOpcode() == ISD::TRUNCATE || N0.getOpcode() == ISD::ZERO_EXTEND) &&
50954       N0.getOperand(0).getOpcode() == N->getOpcode()) {
50955     SDValue TruncExtSrc = N0.getOperand(0);
50956     auto *N1C = dyn_cast<ConstantSDNode>(N1);
50957     auto *N001C = dyn_cast<ConstantSDNode>(TruncExtSrc.getOperand(1));
50958     if (N1C && !N1C->isOpaque() && N001C && !N001C->isOpaque()) {
50959       SDLoc DL(N);
50960       SDValue LHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(0), DL, VT);
50961       SDValue RHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(1), DL, VT);
50962       return DAG.getNode(ISD::XOR, DL, VT, LHS,
50963                          DAG.getNode(ISD::XOR, DL, VT, RHS, N1));
50964     }
50965   }
50966 
50967   return combineFneg(N, DAG, DCI, Subtarget);
50968 }
50969 
50970 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
50971                             TargetLowering::DAGCombinerInfo &DCI,
50972                             const X86Subtarget &Subtarget) {
50973   EVT VT = N->getValueType(0);
50974   unsigned NumBits = VT.getSizeInBits();
50975 
50976   // TODO - Constant Folding.
50977 
50978   // Simplify the inputs.
50979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50980   APInt DemandedMask(APInt::getAllOnes(NumBits));
50981   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
50982     return SDValue(N, 0);
50983 
50984   return SDValue();
50985 }
50986 
50987 static bool isNullFPScalarOrVectorConst(SDValue V) {
50988   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
50989 }
50990 
50991 /// If a value is a scalar FP zero or a vector FP zero (potentially including
50992 /// undefined elements), return a zero constant that may be used to fold away
50993 /// that value. In the case of a vector, the returned constant will not contain
50994 /// undefined elements even if the input parameter does. This makes it suitable
50995 /// to be used as a replacement operand with operations (eg, bitwise-and) where
50996 /// an undef should not propagate.
50997 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
50998                                         const X86Subtarget &Subtarget) {
50999   if (!isNullFPScalarOrVectorConst(V))
51000     return SDValue();
51001 
51002   if (V.getValueType().isVector())
51003     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
51004 
51005   return V;
51006 }
51007 
51008 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
51009                                       const X86Subtarget &Subtarget) {
51010   SDValue N0 = N->getOperand(0);
51011   SDValue N1 = N->getOperand(1);
51012   EVT VT = N->getValueType(0);
51013   SDLoc DL(N);
51014 
51015   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
51016   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
51017         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
51018         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
51019     return SDValue();
51020 
51021   auto isAllOnesConstantFP = [](SDValue V) {
51022     if (V.getSimpleValueType().isVector())
51023       return ISD::isBuildVectorAllOnes(V.getNode());
51024     auto *C = dyn_cast<ConstantFPSDNode>(V);
51025     return C && C->getConstantFPValue()->isAllOnesValue();
51026   };
51027 
51028   // fand (fxor X, -1), Y --> fandn X, Y
51029   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
51030     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
51031 
51032   // fand X, (fxor Y, -1) --> fandn Y, X
51033   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
51034     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
51035 
51036   return SDValue();
51037 }
51038 
51039 /// Do target-specific dag combines on X86ISD::FAND nodes.
51040 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
51041                            const X86Subtarget &Subtarget) {
51042   // FAND(0.0, x) -> 0.0
51043   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
51044     return V;
51045 
51046   // FAND(x, 0.0) -> 0.0
51047   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
51048     return V;
51049 
51050   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
51051     return V;
51052 
51053   return lowerX86FPLogicOp(N, DAG, Subtarget);
51054 }
51055 
51056 /// Do target-specific dag combines on X86ISD::FANDN nodes.
51057 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
51058                             const X86Subtarget &Subtarget) {
51059   // FANDN(0.0, x) -> x
51060   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
51061     return N->getOperand(1);
51062 
51063   // FANDN(x, 0.0) -> 0.0
51064   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
51065     return V;
51066 
51067   return lowerX86FPLogicOp(N, DAG, Subtarget);
51068 }
51069 
51070 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
51071 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
51072                           TargetLowering::DAGCombinerInfo &DCI,
51073                           const X86Subtarget &Subtarget) {
51074   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
51075 
51076   // F[X]OR(0.0, x) -> x
51077   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
51078     return N->getOperand(1);
51079 
51080   // F[X]OR(x, 0.0) -> x
51081   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
51082     return N->getOperand(0);
51083 
51084   if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
51085     return NewVal;
51086 
51087   return lowerX86FPLogicOp(N, DAG, Subtarget);
51088 }
51089 
51090 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
51091 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
51092   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
51093 
51094   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
51095   if (!DAG.getTarget().Options.NoNaNsFPMath ||
51096       !DAG.getTarget().Options.NoSignedZerosFPMath)
51097     return SDValue();
51098 
51099   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
51100   // into FMINC and FMAXC, which are Commutative operations.
51101   unsigned NewOp = 0;
51102   switch (N->getOpcode()) {
51103     default: llvm_unreachable("unknown opcode");
51104     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
51105     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
51106   }
51107 
51108   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
51109                      N->getOperand(0), N->getOperand(1));
51110 }
51111 
51112 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
51113                                      const X86Subtarget &Subtarget) {
51114   if (Subtarget.useSoftFloat())
51115     return SDValue();
51116 
51117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51118 
51119   EVT VT = N->getValueType(0);
51120   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
51121         (Subtarget.hasSSE2() && VT == MVT::f64) ||
51122         (Subtarget.hasFP16() && VT == MVT::f16) ||
51123         (VT.isVector() && TLI.isTypeLegal(VT))))
51124     return SDValue();
51125 
51126   SDValue Op0 = N->getOperand(0);
51127   SDValue Op1 = N->getOperand(1);
51128   SDLoc DL(N);
51129   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
51130 
51131   // If we don't have to respect NaN inputs, this is a direct translation to x86
51132   // min/max instructions.
51133   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
51134     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
51135 
51136   // If one of the operands is known non-NaN use the native min/max instructions
51137   // with the non-NaN input as second operand.
51138   if (DAG.isKnownNeverNaN(Op1))
51139     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
51140   if (DAG.isKnownNeverNaN(Op0))
51141     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
51142 
51143   // If we have to respect NaN inputs, this takes at least 3 instructions.
51144   // Favor a library call when operating on a scalar and minimizing code size.
51145   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
51146     return SDValue();
51147 
51148   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
51149                                          VT);
51150 
51151   // There are 4 possibilities involving NaN inputs, and these are the required
51152   // outputs:
51153   //                   Op1
51154   //               Num     NaN
51155   //            ----------------
51156   //       Num  |  Max  |  Op0 |
51157   // Op0        ----------------
51158   //       NaN  |  Op1  |  NaN |
51159   //            ----------------
51160   //
51161   // The SSE FP max/min instructions were not designed for this case, but rather
51162   // to implement:
51163   //   Min = Op1 < Op0 ? Op1 : Op0
51164   //   Max = Op1 > Op0 ? Op1 : Op0
51165   //
51166   // So they always return Op0 if either input is a NaN. However, we can still
51167   // use those instructions for fmaxnum by selecting away a NaN input.
51168 
51169   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
51170   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
51171   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
51172 
51173   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
51174   // are NaN, the NaN value of Op1 is the result.
51175   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
51176 }
51177 
51178 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
51179                                    TargetLowering::DAGCombinerInfo &DCI) {
51180   EVT VT = N->getValueType(0);
51181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51182 
51183   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
51184   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
51185     return SDValue(N, 0);
51186 
51187   // Convert a full vector load into vzload when not all bits are needed.
51188   SDValue In = N->getOperand(0);
51189   MVT InVT = In.getSimpleValueType();
51190   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
51191       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
51192     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
51193     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
51194     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
51195     MVT MemVT = MVT::getIntegerVT(NumBits);
51196     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
51197     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
51198       SDLoc dl(N);
51199       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
51200                                     DAG.getBitcast(InVT, VZLoad));
51201       DCI.CombineTo(N, Convert);
51202       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
51203       DCI.recursivelyDeleteUnusedNodes(LN);
51204       return SDValue(N, 0);
51205     }
51206   }
51207 
51208   return SDValue();
51209 }
51210 
51211 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
51212                                      TargetLowering::DAGCombinerInfo &DCI) {
51213   bool IsStrict = N->isTargetStrictFPOpcode();
51214   EVT VT = N->getValueType(0);
51215 
51216   // Convert a full vector load into vzload when not all bits are needed.
51217   SDValue In = N->getOperand(IsStrict ? 1 : 0);
51218   MVT InVT = In.getSimpleValueType();
51219   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
51220       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
51221     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
51222     LoadSDNode *LN = cast<LoadSDNode>(In);
51223     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
51224     MVT MemVT = MVT::getFloatingPointVT(NumBits);
51225     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
51226     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
51227       SDLoc dl(N);
51228       if (IsStrict) {
51229         SDValue Convert =
51230             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
51231                         {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
51232         DCI.CombineTo(N, Convert, Convert.getValue(1));
51233       } else {
51234         SDValue Convert =
51235             DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
51236         DCI.CombineTo(N, Convert);
51237       }
51238       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
51239       DCI.recursivelyDeleteUnusedNodes(LN);
51240       return SDValue(N, 0);
51241     }
51242   }
51243 
51244   return SDValue();
51245 }
51246 
51247 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
51248 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
51249                             TargetLowering::DAGCombinerInfo &DCI,
51250                             const X86Subtarget &Subtarget) {
51251   SDValue N0 = N->getOperand(0);
51252   SDValue N1 = N->getOperand(1);
51253   MVT VT = N->getSimpleValueType(0);
51254   int NumElts = VT.getVectorNumElements();
51255   unsigned EltSizeInBits = VT.getScalarSizeInBits();
51256 
51257   // ANDNP(undef, x) -> 0
51258   // ANDNP(x, undef) -> 0
51259   if (N0.isUndef() || N1.isUndef())
51260     return DAG.getConstant(0, SDLoc(N), VT);
51261 
51262   // ANDNP(0, x) -> x
51263   if (ISD::isBuildVectorAllZeros(N0.getNode()))
51264     return N1;
51265 
51266   // ANDNP(x, 0) -> 0
51267   if (ISD::isBuildVectorAllZeros(N1.getNode()))
51268     return DAG.getConstant(0, SDLoc(N), VT);
51269 
51270   // Turn ANDNP back to AND if input is inverted.
51271   if (SDValue Not = IsNOT(N0, DAG))
51272     return DAG.getNode(ISD::AND, SDLoc(N), VT, DAG.getBitcast(VT, Not), N1);
51273 
51274   // Constant Folding
51275   APInt Undefs0, Undefs1;
51276   SmallVector<APInt> EltBits0, EltBits1;
51277   if (getTargetConstantBitsFromNode(N0, EltSizeInBits, Undefs0, EltBits0) &&
51278       getTargetConstantBitsFromNode(N1, EltSizeInBits, Undefs1, EltBits1)) {
51279     SDLoc DL(N);
51280     SmallVector<APInt> ResultBits;
51281     for (int I = 0; I != NumElts; ++I)
51282       ResultBits.push_back(~EltBits0[I] & EltBits1[I]);
51283     APInt ResultUndefs = APInt::getZero(NumElts);
51284     return getConstVector(ResultBits, ResultUndefs, VT, DAG, DL);
51285   }
51286 
51287   // TODO: Constant fold NOT(N0) to allow us to use AND.
51288   // TODO: Do this in IsNOT with suitable oneuse checks?
51289 
51290   // Attempt to recursively combine a bitmask ANDNP with shuffles.
51291   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
51292     SDValue Op(N, 0);
51293     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
51294       return Res;
51295 
51296     // If either operand is a constant mask, then only the elements that aren't
51297     // zero are actually demanded by the other operand.
51298     auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
51299       APInt UndefElts;
51300       SmallVector<APInt> EltBits;
51301       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
51302       APInt DemandedElts = APInt::getAllOnes(NumElts);
51303       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
51304                                         EltBits)) {
51305         DemandedBits.clearAllBits();
51306         DemandedElts.clearAllBits();
51307         for (int I = 0; I != NumElts; ++I) {
51308           if (UndefElts[I]) {
51309             // We can't assume an undef src element gives an undef dst - the
51310             // other src might be zero.
51311             DemandedBits.setAllBits();
51312             DemandedElts.setBit(I);
51313           } else if ((Invert && !EltBits[I].isAllOnes()) ||
51314                      (!Invert && !EltBits[I].isZero())) {
51315             DemandedBits |= Invert ? ~EltBits[I] : EltBits[I];
51316             DemandedElts.setBit(I);
51317           }
51318         }
51319       }
51320       return std::make_pair(DemandedBits, DemandedElts);
51321     };
51322     std::pair<APInt, APInt> Demand0 = GetDemandedMasks(N1);
51323     std::pair<APInt, APInt> Demand1 = GetDemandedMasks(N0, true);
51324 
51325     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51326     if (TLI.SimplifyDemandedVectorElts(N0, Demand0.second, DCI) ||
51327         TLI.SimplifyDemandedVectorElts(N1, Demand1.second, DCI) ||
51328         TLI.SimplifyDemandedBits(N0, Demand0.first, Demand0.second, DCI) ||
51329         TLI.SimplifyDemandedBits(N1, Demand1.first, Demand1.second, DCI)) {
51330       if (N->getOpcode() != ISD::DELETED_NODE)
51331         DCI.AddToWorklist(N);
51332       return SDValue(N, 0);
51333     }
51334   }
51335 
51336   return SDValue();
51337 }
51338 
51339 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
51340                          TargetLowering::DAGCombinerInfo &DCI) {
51341   SDValue N1 = N->getOperand(1);
51342 
51343   // BT ignores high bits in the bit index operand.
51344   unsigned BitWidth = N1.getValueSizeInBits();
51345   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
51346   if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
51347     if (N->getOpcode() != ISD::DELETED_NODE)
51348       DCI.AddToWorklist(N);
51349     return SDValue(N, 0);
51350   }
51351 
51352   return SDValue();
51353 }
51354 
51355 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
51356                                TargetLowering::DAGCombinerInfo &DCI) {
51357   bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
51358   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
51359 
51360   if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
51361     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51362     APInt DemandedElts = APInt::getLowBitsSet(8, 4);
51363     if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, DCI)) {
51364       if (N->getOpcode() != ISD::DELETED_NODE)
51365         DCI.AddToWorklist(N);
51366       return SDValue(N, 0);
51367     }
51368 
51369     // Convert a full vector load into vzload when not all bits are needed.
51370     if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
51371       LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
51372       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
51373         SDLoc dl(N);
51374         if (IsStrict) {
51375           SDValue Convert = DAG.getNode(
51376               N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
51377               {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
51378           DCI.CombineTo(N, Convert, Convert.getValue(1));
51379         } else {
51380           SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
51381                                         DAG.getBitcast(MVT::v8i16, VZLoad));
51382           DCI.CombineTo(N, Convert);
51383         }
51384 
51385         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
51386         DCI.recursivelyDeleteUnusedNodes(LN);
51387         return SDValue(N, 0);
51388       }
51389     }
51390   }
51391 
51392   return SDValue();
51393 }
51394 
51395 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
51396 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
51397   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
51398 
51399   EVT DstVT = N->getValueType(0);
51400 
51401   SDValue N0 = N->getOperand(0);
51402   SDValue N1 = N->getOperand(1);
51403   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
51404 
51405   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
51406     return SDValue();
51407 
51408   // Look through single use any_extends / truncs.
51409   SDValue IntermediateBitwidthOp;
51410   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
51411       N0.hasOneUse()) {
51412     IntermediateBitwidthOp = N0;
51413     N0 = N0.getOperand(0);
51414   }
51415 
51416   // See if we have a single use cmov.
51417   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
51418     return SDValue();
51419 
51420   SDValue CMovOp0 = N0.getOperand(0);
51421   SDValue CMovOp1 = N0.getOperand(1);
51422 
51423   // Make sure both operands are constants.
51424   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
51425       !isa<ConstantSDNode>(CMovOp1.getNode()))
51426     return SDValue();
51427 
51428   SDLoc DL(N);
51429 
51430   // If we looked through an any_extend/trunc above, add one to the constants.
51431   if (IntermediateBitwidthOp) {
51432     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
51433     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
51434     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
51435   }
51436 
51437   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
51438   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
51439 
51440   EVT CMovVT = DstVT;
51441   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
51442   if (DstVT == MVT::i16) {
51443     CMovVT = MVT::i32;
51444     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
51445     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
51446   }
51447 
51448   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
51449                              N0.getOperand(2), N0.getOperand(3));
51450 
51451   if (CMovVT != DstVT)
51452     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
51453 
51454   return CMov;
51455 }
51456 
51457 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
51458                                       const X86Subtarget &Subtarget) {
51459   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
51460 
51461   if (SDValue V = combineSextInRegCmov(N, DAG))
51462     return V;
51463 
51464   EVT VT = N->getValueType(0);
51465   SDValue N0 = N->getOperand(0);
51466   SDValue N1 = N->getOperand(1);
51467   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
51468   SDLoc dl(N);
51469 
51470   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
51471   // both SSE and AVX2 since there is no sign-extended shift right
51472   // operation on a vector with 64-bit elements.
51473   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
51474   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
51475   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
51476                            N0.getOpcode() == ISD::SIGN_EXTEND)) {
51477     SDValue N00 = N0.getOperand(0);
51478 
51479     // EXTLOAD has a better solution on AVX2,
51480     // it may be replaced with X86ISD::VSEXT node.
51481     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
51482       if (!ISD::isNormalLoad(N00.getNode()))
51483         return SDValue();
51484 
51485     // Attempt to promote any comparison mask ops before moving the
51486     // SIGN_EXTEND_INREG in the way.
51487     if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
51488       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
51489 
51490     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
51491       SDValue Tmp =
51492           DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
51493       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
51494     }
51495   }
51496   return SDValue();
51497 }
51498 
51499 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
51500 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
51501 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
51502 /// opportunities to combine math ops, use an LEA, or use a complex addressing
51503 /// mode. This can eliminate extend, add, and shift instructions.
51504 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
51505                                    const X86Subtarget &Subtarget) {
51506   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
51507       Ext->getOpcode() != ISD::ZERO_EXTEND)
51508     return SDValue();
51509 
51510   // TODO: This should be valid for other integer types.
51511   EVT VT = Ext->getValueType(0);
51512   if (VT != MVT::i64)
51513     return SDValue();
51514 
51515   SDValue Add = Ext->getOperand(0);
51516   if (Add.getOpcode() != ISD::ADD)
51517     return SDValue();
51518 
51519   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
51520   bool NSW = Add->getFlags().hasNoSignedWrap();
51521   bool NUW = Add->getFlags().hasNoUnsignedWrap();
51522 
51523   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
51524   // into the 'zext'
51525   if ((Sext && !NSW) || (!Sext && !NUW))
51526     return SDValue();
51527 
51528   // Having a constant operand to the 'add' ensures that we are not increasing
51529   // the instruction count because the constant is extended for free below.
51530   // A constant operand can also become the displacement field of an LEA.
51531   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
51532   if (!AddOp1)
51533     return SDValue();
51534 
51535   // Don't make the 'add' bigger if there's no hope of combining it with some
51536   // other 'add' or 'shl' instruction.
51537   // TODO: It may be profitable to generate simpler LEA instructions in place
51538   // of single 'add' instructions, but the cost model for selecting an LEA
51539   // currently has a high threshold.
51540   bool HasLEAPotential = false;
51541   for (auto *User : Ext->uses()) {
51542     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
51543       HasLEAPotential = true;
51544       break;
51545     }
51546   }
51547   if (!HasLEAPotential)
51548     return SDValue();
51549 
51550   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
51551   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
51552   SDValue AddOp0 = Add.getOperand(0);
51553   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
51554   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
51555 
51556   // The wider add is guaranteed to not wrap because both operands are
51557   // sign-extended.
51558   SDNodeFlags Flags;
51559   Flags.setNoSignedWrap(NSW);
51560   Flags.setNoUnsignedWrap(NUW);
51561   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
51562 }
51563 
51564 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
51565 // operands and the result of CMOV is not used anywhere else - promote CMOV
51566 // itself instead of promoting its result. This could be beneficial, because:
51567 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
51568 //        (or more) pseudo-CMOVs only when they go one-after-another and
51569 //        getting rid of result extension code after CMOV will help that.
51570 //     2) Promotion of constant CMOV arguments is free, hence the
51571 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
51572 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
51573 //        promotion is also good in terms of code-size.
51574 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
51575 //         promotion).
51576 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
51577   SDValue CMovN = Extend->getOperand(0);
51578   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
51579     return SDValue();
51580 
51581   EVT TargetVT = Extend->getValueType(0);
51582   unsigned ExtendOpcode = Extend->getOpcode();
51583   SDLoc DL(Extend);
51584 
51585   EVT VT = CMovN.getValueType();
51586   SDValue CMovOp0 = CMovN.getOperand(0);
51587   SDValue CMovOp1 = CMovN.getOperand(1);
51588 
51589   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
51590       !isa<ConstantSDNode>(CMovOp1.getNode()))
51591     return SDValue();
51592 
51593   // Only extend to i32 or i64.
51594   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
51595     return SDValue();
51596 
51597   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
51598   // are free.
51599   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
51600     return SDValue();
51601 
51602   // If this a zero extend to i64, we should only extend to i32 and use a free
51603   // zero extend to finish.
51604   EVT ExtendVT = TargetVT;
51605   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
51606     ExtendVT = MVT::i32;
51607 
51608   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
51609   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
51610 
51611   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
51612                             CMovN.getOperand(2), CMovN.getOperand(3));
51613 
51614   // Finish extending if needed.
51615   if (ExtendVT != TargetVT)
51616     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
51617 
51618   return Res;
51619 }
51620 
51621 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
51622 // result type.
51623 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
51624                                const X86Subtarget &Subtarget) {
51625   SDValue N0 = N->getOperand(0);
51626   EVT VT = N->getValueType(0);
51627   SDLoc dl(N);
51628 
51629   // Only do this combine with AVX512 for vector extends.
51630   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
51631     return SDValue();
51632 
51633   // Only combine legal element types.
51634   EVT SVT = VT.getVectorElementType();
51635   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
51636       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
51637     return SDValue();
51638 
51639   // We don't have CMPP Instruction for vxf16
51640   if (N0.getOperand(0).getValueType().getVectorElementType() == MVT::f16)
51641     return SDValue();
51642   // We can only do this if the vector size in 256 bits or less.
51643   unsigned Size = VT.getSizeInBits();
51644   if (Size > 256 && Subtarget.useAVX512Regs())
51645     return SDValue();
51646 
51647   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
51648   // that's the only integer compares with we have.
51649   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
51650   if (ISD::isUnsignedIntSetCC(CC))
51651     return SDValue();
51652 
51653   // Only do this combine if the extension will be fully consumed by the setcc.
51654   EVT N00VT = N0.getOperand(0).getValueType();
51655   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
51656   if (Size != MatchingVecType.getSizeInBits())
51657     return SDValue();
51658 
51659   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
51660 
51661   if (N->getOpcode() == ISD::ZERO_EXTEND)
51662     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
51663 
51664   return Res;
51665 }
51666 
51667 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
51668                            TargetLowering::DAGCombinerInfo &DCI,
51669                            const X86Subtarget &Subtarget) {
51670   SDValue N0 = N->getOperand(0);
51671   EVT VT = N->getValueType(0);
51672   SDLoc DL(N);
51673 
51674   // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
51675   if (!DCI.isBeforeLegalizeOps() &&
51676       N0.getOpcode() == X86ISD::SETCC_CARRY) {
51677     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
51678                                  N0->getOperand(1));
51679     bool ReplaceOtherUses = !N0.hasOneUse();
51680     DCI.CombineTo(N, Setcc);
51681     // Replace other uses with a truncate of the widened setcc_carry.
51682     if (ReplaceOtherUses) {
51683       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
51684                                   N0.getValueType(), Setcc);
51685       DCI.CombineTo(N0.getNode(), Trunc);
51686     }
51687 
51688     return SDValue(N, 0);
51689   }
51690 
51691   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
51692     return NewCMov;
51693 
51694   if (!DCI.isBeforeLegalizeOps())
51695     return SDValue();
51696 
51697   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
51698     return V;
51699 
51700   if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), DL, VT, N0,
51701                                                  DAG, DCI, Subtarget))
51702     return V;
51703 
51704   if (VT.isVector()) {
51705     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
51706       return R;
51707 
51708     if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
51709       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
51710   }
51711 
51712   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
51713     return NewAdd;
51714 
51715   return SDValue();
51716 }
51717 
51718 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
51719                           TargetLowering::DAGCombinerInfo &DCI,
51720                           const X86Subtarget &Subtarget) {
51721   SDLoc dl(N);
51722   EVT VT = N->getValueType(0);
51723   bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
51724 
51725   // Let legalize expand this if it isn't a legal type yet.
51726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51727   if (!TLI.isTypeLegal(VT))
51728     return SDValue();
51729 
51730   SDValue A = N->getOperand(IsStrict ? 1 : 0);
51731   SDValue B = N->getOperand(IsStrict ? 2 : 1);
51732   SDValue C = N->getOperand(IsStrict ? 3 : 2);
51733 
51734   // If the operation allows fast-math and the target does not support FMA,
51735   // split this into mul+add to avoid libcall(s).
51736   SDNodeFlags Flags = N->getFlags();
51737   if (!IsStrict && Flags.hasAllowReassociation() &&
51738       TLI.isOperationExpand(ISD::FMA, VT)) {
51739     SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
51740     return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
51741   }
51742 
51743   EVT ScalarVT = VT.getScalarType();
51744   if (((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
51745        !Subtarget.hasAnyFMA()) &&
51746       !(ScalarVT == MVT::f16 && Subtarget.hasFP16()))
51747     return SDValue();
51748 
51749   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
51750     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
51751     bool LegalOperations = !DCI.isBeforeLegalizeOps();
51752     if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
51753                                                        CodeSize)) {
51754       V = NegV;
51755       return true;
51756     }
51757     // Look through extract_vector_elts. If it comes from an FNEG, create a
51758     // new extract from the FNEG input.
51759     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
51760         isNullConstant(V.getOperand(1))) {
51761       SDValue Vec = V.getOperand(0);
51762       if (SDValue NegV = TLI.getCheaperNegatedExpression(
51763               Vec, DAG, LegalOperations, CodeSize)) {
51764         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
51765                         NegV, V.getOperand(1));
51766         return true;
51767       }
51768     }
51769 
51770     return false;
51771   };
51772 
51773   // Do not convert the passthru input of scalar intrinsics.
51774   // FIXME: We could allow negations of the lower element only.
51775   bool NegA = invertIfNegative(A);
51776   bool NegB = invertIfNegative(B);
51777   bool NegC = invertIfNegative(C);
51778 
51779   if (!NegA && !NegB && !NegC)
51780     return SDValue();
51781 
51782   unsigned NewOpcode =
51783       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
51784 
51785   // Propagate fast-math-flags to new FMA node.
51786   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
51787   if (IsStrict) {
51788     assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
51789     return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
51790                        {N->getOperand(0), A, B, C});
51791   } else {
51792     if (N->getNumOperands() == 4)
51793       return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
51794     return DAG.getNode(NewOpcode, dl, VT, A, B, C);
51795   }
51796 }
51797 
51798 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
51799 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
51800 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
51801                                TargetLowering::DAGCombinerInfo &DCI) {
51802   SDLoc dl(N);
51803   EVT VT = N->getValueType(0);
51804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51805   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
51806   bool LegalOperations = !DCI.isBeforeLegalizeOps();
51807 
51808   SDValue N2 = N->getOperand(2);
51809 
51810   SDValue NegN2 =
51811       TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
51812   if (!NegN2)
51813     return SDValue();
51814   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
51815 
51816   if (N->getNumOperands() == 4)
51817     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
51818                        NegN2, N->getOperand(3));
51819   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
51820                      NegN2);
51821 }
51822 
51823 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
51824                            TargetLowering::DAGCombinerInfo &DCI,
51825                            const X86Subtarget &Subtarget) {
51826   SDLoc dl(N);
51827   SDValue N0 = N->getOperand(0);
51828   EVT VT = N->getValueType(0);
51829 
51830   // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
51831   // FIXME: Is this needed? We don't seem to have any tests for it.
51832   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
51833       N0.getOpcode() == X86ISD::SETCC_CARRY) {
51834     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
51835                                  N0->getOperand(1));
51836     bool ReplaceOtherUses = !N0.hasOneUse();
51837     DCI.CombineTo(N, Setcc);
51838     // Replace other uses with a truncate of the widened setcc_carry.
51839     if (ReplaceOtherUses) {
51840       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
51841                                   N0.getValueType(), Setcc);
51842       DCI.CombineTo(N0.getNode(), Trunc);
51843     }
51844 
51845     return SDValue(N, 0);
51846   }
51847 
51848   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
51849     return NewCMov;
51850 
51851   if (DCI.isBeforeLegalizeOps())
51852     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
51853       return V;
51854 
51855   if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), dl, VT, N0,
51856                                                  DAG, DCI, Subtarget))
51857     return V;
51858 
51859   if (VT.isVector())
51860     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
51861       return R;
51862 
51863   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
51864     return NewAdd;
51865 
51866   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
51867     return R;
51868 
51869   // TODO: Combine with any target/faux shuffle.
51870   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
51871       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
51872     SDValue N00 = N0.getOperand(0);
51873     SDValue N01 = N0.getOperand(1);
51874     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
51875     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
51876     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
51877         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
51878       return concatSubVectors(N00, N01, DAG, dl);
51879     }
51880   }
51881 
51882   return SDValue();
51883 }
51884 
51885 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
51886 /// recognizable memcmp expansion.
51887 static bool isOrXorXorTree(SDValue X, bool Root = true) {
51888   if (X.getOpcode() == ISD::OR)
51889     return isOrXorXorTree(X.getOperand(0), false) &&
51890            isOrXorXorTree(X.getOperand(1), false);
51891   if (Root)
51892     return false;
51893   return X.getOpcode() == ISD::XOR;
51894 }
51895 
51896 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
51897 /// expansion.
51898 template <typename F>
51899 static SDValue emitOrXorXorTree(SDValue X, SDLoc &DL, SelectionDAG &DAG,
51900                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
51901   SDValue Op0 = X.getOperand(0);
51902   SDValue Op1 = X.getOperand(1);
51903   if (X.getOpcode() == ISD::OR) {
51904     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
51905     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
51906     if (VecVT != CmpVT)
51907       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
51908     if (HasPT)
51909       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
51910     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
51911   }
51912   if (X.getOpcode() == ISD::XOR) {
51913     SDValue A = SToV(Op0);
51914     SDValue B = SToV(Op1);
51915     if (VecVT != CmpVT)
51916       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
51917     if (HasPT)
51918       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
51919     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
51920   }
51921   llvm_unreachable("Impossible");
51922 }
51923 
51924 /// Try to map a 128-bit or larger integer comparison to vector instructions
51925 /// before type legalization splits it up into chunks.
51926 static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
51927                                                const X86Subtarget &Subtarget) {
51928   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
51929   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
51930 
51931   // We're looking for an oversized integer equality comparison.
51932   SDValue X = SetCC->getOperand(0);
51933   SDValue Y = SetCC->getOperand(1);
51934   EVT OpVT = X.getValueType();
51935   unsigned OpSize = OpVT.getSizeInBits();
51936   if (!OpVT.isScalarInteger() || OpSize < 128)
51937     return SDValue();
51938 
51939   // Ignore a comparison with zero because that gets special treatment in
51940   // EmitTest(). But make an exception for the special case of a pair of
51941   // logically-combined vector-sized operands compared to zero. This pattern may
51942   // be generated by the memcmp expansion pass with oversized integer compares
51943   // (see PR33325).
51944   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
51945   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
51946     return SDValue();
51947 
51948   // Don't perform this combine if constructing the vector will be expensive.
51949   auto IsVectorBitCastCheap = [](SDValue X) {
51950     X = peekThroughBitcasts(X);
51951     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
51952            X.getOpcode() == ISD::LOAD;
51953   };
51954   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
51955       !IsOrXorXorTreeCCZero)
51956     return SDValue();
51957 
51958   EVT VT = SetCC->getValueType(0);
51959   SDLoc DL(SetCC);
51960 
51961   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
51962   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
51963   // Otherwise use PCMPEQ (plus AND) and mask testing.
51964   bool NoImplicitFloatOps =
51965       DAG.getMachineFunction().getFunction().hasFnAttribute(
51966           Attribute::NoImplicitFloat);
51967   if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
51968       ((OpSize == 128 && Subtarget.hasSSE2()) ||
51969        (OpSize == 256 && Subtarget.hasAVX()) ||
51970        (OpSize == 512 && Subtarget.useAVX512Regs()))) {
51971     bool HasPT = Subtarget.hasSSE41();
51972 
51973     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
51974     // vector registers are essentially free. (Technically, widening registers
51975     // prevents load folding, but the tradeoff is worth it.)
51976     bool PreferKOT = Subtarget.preferMaskRegisters();
51977     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
51978 
51979     EVT VecVT = MVT::v16i8;
51980     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
51981     if (OpSize == 256) {
51982       VecVT = MVT::v32i8;
51983       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
51984     }
51985     EVT CastVT = VecVT;
51986     bool NeedsAVX512FCast = false;
51987     if (OpSize == 512 || NeedZExt) {
51988       if (Subtarget.hasBWI()) {
51989         VecVT = MVT::v64i8;
51990         CmpVT = MVT::v64i1;
51991         if (OpSize == 512)
51992           CastVT = VecVT;
51993       } else {
51994         VecVT = MVT::v16i32;
51995         CmpVT = MVT::v16i1;
51996         CastVT = OpSize == 512 ? VecVT :
51997                  OpSize == 256 ? MVT::v8i32 : MVT::v4i32;
51998         NeedsAVX512FCast = true;
51999       }
52000     }
52001 
52002     auto ScalarToVector = [&](SDValue X) -> SDValue {
52003       bool TmpZext = false;
52004       EVT TmpCastVT = CastVT;
52005       if (X.getOpcode() == ISD::ZERO_EXTEND) {
52006         SDValue OrigX = X.getOperand(0);
52007         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
52008         if (OrigSize < OpSize) {
52009           if (OrigSize == 128) {
52010             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
52011             X = OrigX;
52012             TmpZext = true;
52013           } else if (OrigSize == 256) {
52014             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
52015             X = OrigX;
52016             TmpZext = true;
52017           }
52018         }
52019       }
52020       X = DAG.getBitcast(TmpCastVT, X);
52021       if (!NeedZExt && !TmpZext)
52022         return X;
52023       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
52024                          DAG.getConstant(0, DL, VecVT), X,
52025                          DAG.getVectorIdxConstant(0, DL));
52026     };
52027 
52028     SDValue Cmp;
52029     if (IsOrXorXorTreeCCZero) {
52030       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
52031       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
52032       // Use 2 vector equality compares and 'and' the results before doing a
52033       // MOVMSK.
52034       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
52035     } else {
52036       SDValue VecX = ScalarToVector(X);
52037       SDValue VecY = ScalarToVector(Y);
52038       if (VecVT != CmpVT) {
52039         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
52040       } else if (HasPT) {
52041         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
52042       } else {
52043         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
52044       }
52045     }
52046     // AVX512 should emit a setcc that will lower to kortest.
52047     if (VecVT != CmpVT) {
52048       EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64 :
52049                    CmpVT == MVT::v32i1 ? MVT::i32 : MVT::i16;
52050       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
52051                           DAG.getConstant(0, DL, KRegVT), CC);
52052     }
52053     if (HasPT) {
52054       SDValue BCCmp = DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64,
52055                                      Cmp);
52056       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
52057       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
52058       SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
52059       return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
52060     }
52061     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
52062     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
52063     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
52064     assert(Cmp.getValueType() == MVT::v16i8 &&
52065            "Non 128-bit vector on pre-SSE41 target");
52066     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
52067     SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
52068     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
52069   }
52070 
52071   return SDValue();
52072 }
52073 
52074 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
52075                             TargetLowering::DAGCombinerInfo &DCI,
52076                             const X86Subtarget &Subtarget) {
52077   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
52078   const SDValue LHS = N->getOperand(0);
52079   const SDValue RHS = N->getOperand(1);
52080   EVT VT = N->getValueType(0);
52081   EVT OpVT = LHS.getValueType();
52082   SDLoc DL(N);
52083 
52084   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
52085     if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
52086       return V;
52087 
52088     if (VT == MVT::i1 && isNullConstant(RHS)) {
52089       SDValue X86CC;
52090       if (SDValue V =
52091               MatchVectorAllZeroTest(LHS, CC, DL, Subtarget, DAG, X86CC))
52092         return DAG.getNode(ISD::TRUNCATE, DL, VT,
52093                            DAG.getNode(X86ISD::SETCC, DL, MVT::i8, X86CC, V));
52094     }
52095 
52096     if (OpVT.isScalarInteger()) {
52097       // cmpeq(or(X,Y),X) --> cmpeq(and(~X,Y),0)
52098       // cmpne(or(X,Y),X) --> cmpne(and(~X,Y),0)
52099       auto MatchOrCmpEq = [&](SDValue N0, SDValue N1) {
52100         if (N0.getOpcode() == ISD::OR && N0->hasOneUse()) {
52101           if (N0.getOperand(0) == N1)
52102             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
52103                                N0.getOperand(1));
52104           if (N0.getOperand(1) == N1)
52105             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
52106                                N0.getOperand(0));
52107         }
52108         return SDValue();
52109       };
52110       if (SDValue AndN = MatchOrCmpEq(LHS, RHS))
52111         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52112       if (SDValue AndN = MatchOrCmpEq(RHS, LHS))
52113         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52114 
52115       // cmpeq(and(X,Y),Y) --> cmpeq(and(~X,Y),0)
52116       // cmpne(and(X,Y),Y) --> cmpne(and(~X,Y),0)
52117       auto MatchAndCmpEq = [&](SDValue N0, SDValue N1) {
52118         if (N0.getOpcode() == ISD::AND && N0->hasOneUse()) {
52119           if (N0.getOperand(0) == N1)
52120             return DAG.getNode(ISD::AND, DL, OpVT, N1,
52121                                DAG.getNOT(DL, N0.getOperand(1), OpVT));
52122           if (N0.getOperand(1) == N1)
52123             return DAG.getNode(ISD::AND, DL, OpVT, N1,
52124                                DAG.getNOT(DL, N0.getOperand(0), OpVT));
52125         }
52126         return SDValue();
52127       };
52128       if (SDValue AndN = MatchAndCmpEq(LHS, RHS))
52129         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52130       if (SDValue AndN = MatchAndCmpEq(RHS, LHS))
52131         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52132 
52133       // cmpeq(trunc(x),0) --> cmpeq(x,0)
52134       // cmpne(trunc(x),0) --> cmpne(x,0)
52135       // iff x upper bits are zero.
52136       // TODO: Add support for RHS to be truncate as well?
52137       if (LHS.getOpcode() == ISD::TRUNCATE &&
52138           LHS.getOperand(0).getScalarValueSizeInBits() >= 32 &&
52139           isNullConstant(RHS) && !DCI.isBeforeLegalize()) {
52140         EVT SrcVT = LHS.getOperand(0).getValueType();
52141         APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
52142                                                 OpVT.getScalarSizeInBits());
52143         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52144         if (DAG.MaskedValueIsZero(LHS.getOperand(0), UpperBits) &&
52145             TLI.isTypeLegal(LHS.getOperand(0).getValueType()))
52146           return DAG.getSetCC(DL, VT, LHS.getOperand(0),
52147                               DAG.getConstant(0, DL, SrcVT), CC);
52148       }
52149     }
52150   }
52151 
52152   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
52153       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
52154     // Using temporaries to avoid messing up operand ordering for later
52155     // transformations if this doesn't work.
52156     SDValue Op0 = LHS;
52157     SDValue Op1 = RHS;
52158     ISD::CondCode TmpCC = CC;
52159     // Put build_vector on the right.
52160     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
52161       std::swap(Op0, Op1);
52162       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
52163     }
52164 
52165     bool IsSEXT0 =
52166         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
52167         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
52168     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
52169 
52170     if (IsSEXT0 && IsVZero1) {
52171       assert(VT == Op0.getOperand(0).getValueType() &&
52172              "Unexpected operand type");
52173       if (TmpCC == ISD::SETGT)
52174         return DAG.getConstant(0, DL, VT);
52175       if (TmpCC == ISD::SETLE)
52176         return DAG.getConstant(1, DL, VT);
52177       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
52178         return DAG.getNOT(DL, Op0.getOperand(0), VT);
52179 
52180       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
52181              "Unexpected condition code!");
52182       return Op0.getOperand(0);
52183     }
52184   }
52185 
52186   // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
52187   // pre-promote its result type since vXi1 vectors don't get promoted
52188   // during type legalization.
52189   // NOTE: The element count check is to ignore operand types that need to
52190   // go through type promotion to a 128-bit vector.
52191   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
52192       VT.getVectorElementType() == MVT::i1 &&
52193       (OpVT.getVectorElementType() == MVT::i8 ||
52194        OpVT.getVectorElementType() == MVT::i16)) {
52195     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
52196     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
52197   }
52198 
52199   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
52200   // to avoid scalarization via legalization because v4i32 is not a legal type.
52201   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
52202       LHS.getValueType() == MVT::v4f32)
52203     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
52204 
52205   // X pred 0.0 --> X pred -X
52206   // If the negation of X already exists, use it in the comparison. This removes
52207   // the need to materialize 0.0 and allows matching to SSE's MIN/MAX
52208   // instructions in patterns with a 'select' node.
52209   if (isNullFPScalarOrVectorConst(RHS)) {
52210     SDVTList FNegVT = DAG.getVTList(OpVT);
52211     if (SDNode *FNeg = DAG.getNodeIfExists(ISD::FNEG, FNegVT, {LHS}))
52212       return DAG.getSetCC(DL, VT, LHS, SDValue(FNeg, 0), CC);
52213   }
52214 
52215   return SDValue();
52216 }
52217 
52218 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
52219                              TargetLowering::DAGCombinerInfo &DCI,
52220                              const X86Subtarget &Subtarget) {
52221   SDValue Src = N->getOperand(0);
52222   MVT SrcVT = Src.getSimpleValueType();
52223   MVT VT = N->getSimpleValueType(0);
52224   unsigned NumBits = VT.getScalarSizeInBits();
52225   unsigned NumElts = SrcVT.getVectorNumElements();
52226   unsigned NumBitsPerElt = SrcVT.getScalarSizeInBits();
52227   assert(VT == MVT::i32 && NumElts <= NumBits && "Unexpected MOVMSK types");
52228 
52229   // Perform constant folding.
52230   APInt UndefElts;
52231   SmallVector<APInt, 32> EltBits;
52232   if (getTargetConstantBitsFromNode(Src, NumBitsPerElt, UndefElts, EltBits)) {
52233     APInt Imm(32, 0);
52234     for (unsigned Idx = 0; Idx != NumElts; ++Idx)
52235       if (!UndefElts[Idx] && EltBits[Idx].isNegative())
52236         Imm.setBit(Idx);
52237 
52238     return DAG.getConstant(Imm, SDLoc(N), VT);
52239   }
52240 
52241   // Look through int->fp bitcasts that don't change the element width.
52242   unsigned EltWidth = SrcVT.getScalarSizeInBits();
52243   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
52244       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
52245     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
52246 
52247   // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
52248   // with scalar comparisons.
52249   if (SDValue NotSrc = IsNOT(Src, DAG)) {
52250     SDLoc DL(N);
52251     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
52252     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
52253     return DAG.getNode(ISD::XOR, DL, VT,
52254                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
52255                        DAG.getConstant(NotMask, DL, VT));
52256   }
52257 
52258   // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
52259   // results with scalar comparisons.
52260   if (Src.getOpcode() == X86ISD::PCMPGT &&
52261       ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
52262     SDLoc DL(N);
52263     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
52264     return DAG.getNode(ISD::XOR, DL, VT,
52265                        DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
52266                        DAG.getConstant(NotMask, DL, VT));
52267   }
52268 
52269   // Fold movmsk(icmp_eq(and(x,c1),0)) -> movmsk(not(shl(x,c2)))
52270   // iff pow2splat(c1).
52271   if (Src.getOpcode() == X86ISD::PCMPEQ &&
52272       Src.getOperand(0).getOpcode() == ISD::AND &&
52273       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
52274     SDValue LHS = Src.getOperand(0).getOperand(0);
52275     SDValue RHS = Src.getOperand(0).getOperand(1);
52276     KnownBits KnownRHS = DAG.computeKnownBits(RHS);
52277     if (KnownRHS.isConstant() && KnownRHS.getConstant().isPowerOf2()) {
52278       SDLoc DL(N);
52279       MVT ShiftVT = SrcVT;
52280       if (ShiftVT.getScalarType() == MVT::i8) {
52281         // vXi8 shifts - we only care about the signbit so can use PSLLW.
52282         ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
52283         LHS = DAG.getBitcast(ShiftVT, LHS);
52284       }
52285       unsigned ShiftAmt = KnownRHS.getConstant().countLeadingZeros();
52286       LHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT, LHS,
52287                                        ShiftAmt, DAG);
52288       LHS = DAG.getNOT(DL, DAG.getBitcast(SrcVT, LHS), SrcVT);
52289       return DAG.getNode(X86ISD::MOVMSK, DL, VT, LHS);
52290     }
52291   }
52292 
52293   // Simplify the inputs.
52294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52295   APInt DemandedMask(APInt::getAllOnes(NumBits));
52296   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
52297     return SDValue(N, 0);
52298 
52299   return SDValue();
52300 }
52301 
52302 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
52303                                        TargetLowering::DAGCombinerInfo &DCI,
52304                                        const X86Subtarget &Subtarget) {
52305   auto *MemOp = cast<X86MaskedGatherScatterSDNode>(N);
52306   SDValue BasePtr = MemOp->getBasePtr();
52307   SDValue Index = MemOp->getIndex();
52308   SDValue Scale = MemOp->getScale();
52309   SDValue Mask = MemOp->getMask();
52310 
52311   // Attempt to fold an index scale into the scale value directly.
52312   // For smaller indices, implicit sext is performed BEFORE scale, preventing
52313   // this fold under most circumstances.
52314   // TODO: Move this into X86DAGToDAGISel::matchVectorAddressRecursively?
52315   if ((Index.getOpcode() == X86ISD::VSHLI ||
52316        (Index.getOpcode() == ISD::ADD &&
52317         Index.getOperand(0) == Index.getOperand(1))) &&
52318       isa<ConstantSDNode>(Scale) &&
52319       BasePtr.getScalarValueSizeInBits() == Index.getScalarValueSizeInBits()) {
52320     unsigned ShiftAmt =
52321         Index.getOpcode() == ISD::ADD ? 1 : Index.getConstantOperandVal(1);
52322     uint64_t ScaleAmt = cast<ConstantSDNode>(Scale)->getZExtValue();
52323     uint64_t NewScaleAmt = ScaleAmt * (1ULL << ShiftAmt);
52324     if (isPowerOf2_64(NewScaleAmt) && NewScaleAmt <= 8) {
52325       SDValue NewIndex = Index.getOperand(0);
52326       SDValue NewScale =
52327           DAG.getTargetConstant(NewScaleAmt, SDLoc(N), Scale.getValueType());
52328       if (N->getOpcode() == X86ISD::MGATHER)
52329         return getAVX2GatherNode(N->getOpcode(), SDValue(N, 0), DAG,
52330                                  MemOp->getOperand(1), Mask,
52331                                  MemOp->getBasePtr(), NewIndex, NewScale,
52332                                  MemOp->getChain(), Subtarget);
52333       if (N->getOpcode() == X86ISD::MSCATTER)
52334         return getScatterNode(N->getOpcode(), SDValue(N, 0), DAG,
52335                               MemOp->getOperand(1), Mask, MemOp->getBasePtr(),
52336                               NewIndex, NewScale, MemOp->getChain(), Subtarget);
52337     }
52338   }
52339 
52340   // With vector masks we only demand the upper bit of the mask.
52341   if (Mask.getScalarValueSizeInBits() != 1) {
52342     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52343     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
52344     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
52345       if (N->getOpcode() != ISD::DELETED_NODE)
52346         DCI.AddToWorklist(N);
52347       return SDValue(N, 0);
52348     }
52349   }
52350 
52351   return SDValue();
52352 }
52353 
52354 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
52355                                     SDValue Index, SDValue Base, SDValue Scale,
52356                                     SelectionDAG &DAG) {
52357   SDLoc DL(GorS);
52358 
52359   if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
52360     SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
52361                       Gather->getMask(), Base, Index, Scale } ;
52362     return DAG.getMaskedGather(Gather->getVTList(),
52363                                Gather->getMemoryVT(), DL, Ops,
52364                                Gather->getMemOperand(),
52365                                Gather->getIndexType(),
52366                                Gather->getExtensionType());
52367   }
52368   auto *Scatter = cast<MaskedScatterSDNode>(GorS);
52369   SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
52370                     Scatter->getMask(), Base, Index, Scale };
52371   return DAG.getMaskedScatter(Scatter->getVTList(),
52372                               Scatter->getMemoryVT(), DL,
52373                               Ops, Scatter->getMemOperand(),
52374                               Scatter->getIndexType(),
52375                               Scatter->isTruncatingStore());
52376 }
52377 
52378 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
52379                                     TargetLowering::DAGCombinerInfo &DCI) {
52380   SDLoc DL(N);
52381   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
52382   SDValue Index = GorS->getIndex();
52383   SDValue Base = GorS->getBasePtr();
52384   SDValue Scale = GorS->getScale();
52385 
52386   if (DCI.isBeforeLegalize()) {
52387     unsigned IndexWidth = Index.getScalarValueSizeInBits();
52388 
52389     // Shrink constant indices if they are larger than 32-bits.
52390     // Only do this before legalize types since v2i64 could become v2i32.
52391     // FIXME: We could check that the type is legal if we're after legalize
52392     // types, but then we would need to construct test cases where that happens.
52393     // FIXME: We could support more than just constant vectors, but we need to
52394     // careful with costing. A truncate that can be optimized out would be fine.
52395     // Otherwise we might only want to create a truncate if it avoids a split.
52396     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
52397       if (BV->isConstant() && IndexWidth > 32 &&
52398           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
52399         EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
52400         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
52401         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
52402       }
52403     }
52404 
52405     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
52406     // there are sufficient sign bits. Only do this before legalize types to
52407     // avoid creating illegal types in truncate.
52408     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
52409          Index.getOpcode() == ISD::ZERO_EXTEND) &&
52410         IndexWidth > 32 &&
52411         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
52412         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
52413       EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
52414       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
52415       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
52416     }
52417   }
52418 
52419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52420   EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
52421   // Try to move splat constant adders from the index operand to the base
52422   // pointer operand. Taking care to multiply by the scale. We can only do
52423   // this when index element type is the same as the pointer type.
52424   // Otherwise we need to be sure the math doesn't wrap before the scale.
52425   if (Index.getOpcode() == ISD::ADD &&
52426       Index.getValueType().getVectorElementType() == PtrVT &&
52427       isa<ConstantSDNode>(Scale)) {
52428     uint64_t ScaleAmt = cast<ConstantSDNode>(Scale)->getZExtValue();
52429     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index.getOperand(1))) {
52430       BitVector UndefElts;
52431       if (ConstantSDNode *C = BV->getConstantSplatNode(&UndefElts)) {
52432         // FIXME: Allow non-constant?
52433         if (UndefElts.none()) {
52434           // Apply the scale.
52435           APInt Adder = C->getAPIntValue() * ScaleAmt;
52436           // Add it to the existing base.
52437           Base = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
52438                              DAG.getConstant(Adder, DL, PtrVT));
52439           Index = Index.getOperand(0);
52440           return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
52441         }
52442       }
52443 
52444       // It's also possible base is just a constant. In that case, just
52445       // replace it with 0 and move the displacement into the index.
52446       if (BV->isConstant() && isa<ConstantSDNode>(Base) &&
52447           isOneConstant(Scale)) {
52448         SDValue Splat = DAG.getSplatBuildVector(Index.getValueType(), DL, Base);
52449         // Combine the constant build_vector and the constant base.
52450         Splat = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
52451                             Index.getOperand(1), Splat);
52452         // Add to the LHS of the original Index add.
52453         Index = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
52454                             Index.getOperand(0), Splat);
52455         Base = DAG.getConstant(0, DL, Base.getValueType());
52456         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
52457       }
52458     }
52459   }
52460 
52461   if (DCI.isBeforeLegalizeOps()) {
52462     unsigned IndexWidth = Index.getScalarValueSizeInBits();
52463 
52464     // Make sure the index is either i32 or i64
52465     if (IndexWidth != 32 && IndexWidth != 64) {
52466       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
52467       EVT IndexVT = Index.getValueType().changeVectorElementType(EltVT);
52468       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
52469       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
52470     }
52471   }
52472 
52473   // With vector masks we only demand the upper bit of the mask.
52474   SDValue Mask = GorS->getMask();
52475   if (Mask.getScalarValueSizeInBits() != 1) {
52476     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52477     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
52478     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
52479       if (N->getOpcode() != ISD::DELETED_NODE)
52480         DCI.AddToWorklist(N);
52481       return SDValue(N, 0);
52482     }
52483   }
52484 
52485   return SDValue();
52486 }
52487 
52488 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
52489 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
52490                                const X86Subtarget &Subtarget) {
52491   SDLoc DL(N);
52492   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
52493   SDValue EFLAGS = N->getOperand(1);
52494 
52495   // Try to simplify the EFLAGS and condition code operands.
52496   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
52497     return getSETCC(CC, Flags, DL, DAG);
52498 
52499   return SDValue();
52500 }
52501 
52502 /// Optimize branch condition evaluation.
52503 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
52504                              const X86Subtarget &Subtarget) {
52505   SDLoc DL(N);
52506   SDValue EFLAGS = N->getOperand(3);
52507   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
52508 
52509   // Try to simplify the EFLAGS and condition code operands.
52510   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
52511   // RAUW them under us.
52512   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
52513     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
52514     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
52515                        N->getOperand(1), Cond, Flags);
52516   }
52517 
52518   return SDValue();
52519 }
52520 
52521 // TODO: Could we move this to DAGCombine?
52522 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
52523                                                   SelectionDAG &DAG) {
52524   // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
52525   // to optimize away operation when it's from a constant.
52526   //
52527   // The general transformation is:
52528   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
52529   //       AND(VECTOR_CMP(x,y), constant2)
52530   //    constant2 = UNARYOP(constant)
52531 
52532   // Early exit if this isn't a vector operation, the operand of the
52533   // unary operation isn't a bitwise AND, or if the sizes of the operations
52534   // aren't the same.
52535   EVT VT = N->getValueType(0);
52536   bool IsStrict = N->isStrictFPOpcode();
52537   unsigned NumEltBits = VT.getScalarSizeInBits();
52538   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
52539   if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
52540       DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
52541       VT.getSizeInBits() != Op0.getValueSizeInBits())
52542     return SDValue();
52543 
52544   // Now check that the other operand of the AND is a constant. We could
52545   // make the transformation for non-constant splats as well, but it's unclear
52546   // that would be a benefit as it would not eliminate any operations, just
52547   // perform one more step in scalar code before moving to the vector unit.
52548   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
52549     // Bail out if the vector isn't a constant.
52550     if (!BV->isConstant())
52551       return SDValue();
52552 
52553     // Everything checks out. Build up the new and improved node.
52554     SDLoc DL(N);
52555     EVT IntVT = BV->getValueType(0);
52556     // Create a new constant of the appropriate type for the transformed
52557     // DAG.
52558     SDValue SourceConst;
52559     if (IsStrict)
52560       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
52561                                 {N->getOperand(0), SDValue(BV, 0)});
52562     else
52563       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
52564     // The AND node needs bitcasts to/from an integer vector type around it.
52565     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
52566     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
52567                                  MaskConst);
52568     SDValue Res = DAG.getBitcast(VT, NewAnd);
52569     if (IsStrict)
52570       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
52571     return Res;
52572   }
52573 
52574   return SDValue();
52575 }
52576 
52577 /// If we are converting a value to floating-point, try to replace scalar
52578 /// truncate of an extracted vector element with a bitcast. This tries to keep
52579 /// the sequence on XMM registers rather than moving between vector and GPRs.
52580 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
52581   // TODO: This is currently only used by combineSIntToFP, but it is generalized
52582   //       to allow being called by any similar cast opcode.
52583   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
52584   SDValue Trunc = N->getOperand(0);
52585   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
52586     return SDValue();
52587 
52588   SDValue ExtElt = Trunc.getOperand(0);
52589   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
52590       !isNullConstant(ExtElt.getOperand(1)))
52591     return SDValue();
52592 
52593   EVT TruncVT = Trunc.getValueType();
52594   EVT SrcVT = ExtElt.getValueType();
52595   unsigned DestWidth = TruncVT.getSizeInBits();
52596   unsigned SrcWidth = SrcVT.getSizeInBits();
52597   if (SrcWidth % DestWidth != 0)
52598     return SDValue();
52599 
52600   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
52601   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
52602   unsigned VecWidth = SrcVecVT.getSizeInBits();
52603   unsigned NumElts = VecWidth / DestWidth;
52604   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
52605   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
52606   SDLoc DL(N);
52607   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
52608                                   BitcastVec, ExtElt.getOperand(1));
52609   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
52610 }
52611 
52612 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
52613                                const X86Subtarget &Subtarget) {
52614   bool IsStrict = N->isStrictFPOpcode();
52615   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
52616   EVT VT = N->getValueType(0);
52617   EVT InVT = Op0.getValueType();
52618 
52619   // UINT_TO_FP(vXi1~15)  -> UINT_TO_FP(ZEXT(vXi1~15  to vXi16))
52620   // UINT_TO_FP(vXi17~31) -> UINT_TO_FP(ZEXT(vXi17~31 to vXi32))
52621   // UINT_TO_FP(vXi33~63) -> UINT_TO_FP(ZEXT(vXi33~63 to vXi64))
52622   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
52623     unsigned ScalarSize = InVT.getScalarSizeInBits();
52624     if (ScalarSize == 16 || ScalarSize == 32 || ScalarSize >= 64)
52625       return SDValue();
52626     SDLoc dl(N);
52627     EVT DstVT = EVT::getVectorVT(*DAG.getContext(),
52628                                  ScalarSize < 16   ? MVT::i16
52629                                  : ScalarSize < 32 ? MVT::i32
52630                                                    : MVT::i64,
52631                                  InVT.getVectorNumElements());
52632     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
52633     if (IsStrict)
52634       return DAG.getNode(ISD::STRICT_UINT_TO_FP, dl, {VT, MVT::Other},
52635                          {N->getOperand(0), P});
52636     return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
52637   }
52638 
52639   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
52640   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
52641   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
52642   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
52643       VT.getScalarType() != MVT::f16) {
52644     SDLoc dl(N);
52645     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
52646     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
52647 
52648     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
52649     if (IsStrict)
52650       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
52651                          {N->getOperand(0), P});
52652     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
52653   }
52654 
52655   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
52656   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
52657   // the optimization here.
52658   if (DAG.SignBitIsZero(Op0)) {
52659     if (IsStrict)
52660       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
52661                          {N->getOperand(0), Op0});
52662     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
52663   }
52664 
52665   return SDValue();
52666 }
52667 
52668 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
52669                                TargetLowering::DAGCombinerInfo &DCI,
52670                                const X86Subtarget &Subtarget) {
52671   // First try to optimize away the conversion entirely when it's
52672   // conditionally from a constant. Vectors only.
52673   bool IsStrict = N->isStrictFPOpcode();
52674   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
52675     return Res;
52676 
52677   // Now move on to more general possibilities.
52678   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
52679   EVT VT = N->getValueType(0);
52680   EVT InVT = Op0.getValueType();
52681 
52682   // SINT_TO_FP(vXi1~15)  -> SINT_TO_FP(SEXT(vXi1~15  to vXi16))
52683   // SINT_TO_FP(vXi17~31) -> SINT_TO_FP(SEXT(vXi17~31 to vXi32))
52684   // SINT_TO_FP(vXi33~63) -> SINT_TO_FP(SEXT(vXi33~63 to vXi64))
52685   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
52686     unsigned ScalarSize = InVT.getScalarSizeInBits();
52687     if (ScalarSize == 16 || ScalarSize == 32 || ScalarSize >= 64)
52688       return SDValue();
52689     SDLoc dl(N);
52690     EVT DstVT = EVT::getVectorVT(*DAG.getContext(),
52691                                  ScalarSize < 16   ? MVT::i16
52692                                  : ScalarSize < 32 ? MVT::i32
52693                                                    : MVT::i64,
52694                                  InVT.getVectorNumElements());
52695     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
52696     if (IsStrict)
52697       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
52698                          {N->getOperand(0), P});
52699     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
52700   }
52701 
52702   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
52703   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
52704   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
52705   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
52706       VT.getScalarType() != MVT::f16) {
52707     SDLoc dl(N);
52708     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
52709     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
52710     if (IsStrict)
52711       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
52712                          {N->getOperand(0), P});
52713     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
52714   }
52715 
52716   // Without AVX512DQ we only support i64 to float scalar conversion. For both
52717   // vectors and scalars, see if we know that the upper bits are all the sign
52718   // bit, in which case we can truncate the input to i32 and convert from that.
52719   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
52720     unsigned BitWidth = InVT.getScalarSizeInBits();
52721     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
52722     if (NumSignBits >= (BitWidth - 31)) {
52723       EVT TruncVT = MVT::i32;
52724       if (InVT.isVector())
52725         TruncVT = InVT.changeVectorElementType(TruncVT);
52726       SDLoc dl(N);
52727       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
52728         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
52729         if (IsStrict)
52730           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
52731                              {N->getOperand(0), Trunc});
52732         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
52733       }
52734       // If we're after legalize and the type is v2i32 we need to shuffle and
52735       // use CVTSI2P.
52736       assert(InVT == MVT::v2i64 && "Unexpected VT!");
52737       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
52738       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
52739                                           { 0, 2, -1, -1 });
52740       if (IsStrict)
52741         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
52742                            {N->getOperand(0), Shuf});
52743       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
52744     }
52745   }
52746 
52747   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
52748   // a 32-bit target where SSE doesn't support i64->FP operations.
52749   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
52750       Op0.getOpcode() == ISD::LOAD) {
52751     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
52752 
52753     // This transformation is not supported if the result type is f16 or f128.
52754     if (VT == MVT::f16 || VT == MVT::f128)
52755       return SDValue();
52756 
52757     // If we have AVX512DQ we can use packed conversion instructions unless
52758     // the VT is f80.
52759     if (Subtarget.hasDQI() && VT != MVT::f80)
52760       return SDValue();
52761 
52762     if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
52763         Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
52764       std::pair<SDValue, SDValue> Tmp =
52765           Subtarget.getTargetLowering()->BuildFILD(
52766               VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
52767               Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
52768       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
52769       return Tmp.first;
52770     }
52771   }
52772 
52773   if (IsStrict)
52774     return SDValue();
52775 
52776   if (SDValue V = combineToFPTruncExtElt(N, DAG))
52777     return V;
52778 
52779   return SDValue();
52780 }
52781 
52782 static bool needCarryOrOverflowFlag(SDValue Flags) {
52783   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
52784 
52785   for (const SDNode *User : Flags->uses()) {
52786     X86::CondCode CC;
52787     switch (User->getOpcode()) {
52788     default:
52789       // Be conservative.
52790       return true;
52791     case X86ISD::SETCC:
52792     case X86ISD::SETCC_CARRY:
52793       CC = (X86::CondCode)User->getConstantOperandVal(0);
52794       break;
52795     case X86ISD::BRCOND:
52796     case X86ISD::CMOV:
52797       CC = (X86::CondCode)User->getConstantOperandVal(2);
52798       break;
52799     }
52800 
52801     switch (CC) {
52802     default: break;
52803     case X86::COND_A: case X86::COND_AE:
52804     case X86::COND_B: case X86::COND_BE:
52805     case X86::COND_O: case X86::COND_NO:
52806     case X86::COND_G: case X86::COND_GE:
52807     case X86::COND_L: case X86::COND_LE:
52808       return true;
52809     }
52810   }
52811 
52812   return false;
52813 }
52814 
52815 static bool onlyZeroFlagUsed(SDValue Flags) {
52816   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
52817 
52818   for (const SDNode *User : Flags->uses()) {
52819     unsigned CCOpNo;
52820     switch (User->getOpcode()) {
52821     default:
52822       // Be conservative.
52823       return false;
52824     case X86ISD::SETCC:
52825     case X86ISD::SETCC_CARRY:
52826       CCOpNo = 0;
52827       break;
52828     case X86ISD::BRCOND:
52829     case X86ISD::CMOV:
52830       CCOpNo = 2;
52831       break;
52832     }
52833 
52834     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
52835     if (CC != X86::COND_E && CC != X86::COND_NE)
52836       return false;
52837   }
52838 
52839   return true;
52840 }
52841 
52842 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
52843 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
52844 /// with CMP+{ADC, SBB}.
52845 /// Also try (ADD/SUB)+(AND(SRL,1)) bit extraction pattern with BT+{ADC, SBB}.
52846 static SDValue combineAddOrSubToADCOrSBB(bool IsSub, const SDLoc &DL, EVT VT,
52847                                          SDValue X, SDValue Y,
52848                                          SelectionDAG &DAG,
52849                                          bool ZeroSecondOpOnly = false) {
52850   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
52851     return SDValue();
52852 
52853   // Look through a one-use zext.
52854   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse())
52855     Y = Y.getOperand(0);
52856 
52857   X86::CondCode CC;
52858   SDValue EFLAGS;
52859   if (Y.getOpcode() == X86ISD::SETCC && Y.hasOneUse()) {
52860     CC = (X86::CondCode)Y.getConstantOperandVal(0);
52861     EFLAGS = Y.getOperand(1);
52862   } else if (Y.getOpcode() == ISD::AND && isOneConstant(Y.getOperand(1)) &&
52863              Y.hasOneUse()) {
52864     EFLAGS = LowerAndToBT(Y, ISD::SETNE, DL, DAG, CC);
52865   }
52866 
52867   if (!EFLAGS)
52868     return SDValue();
52869 
52870   // If X is -1 or 0, then we have an opportunity to avoid constants required in
52871   // the general case below.
52872   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
52873   if (ConstantX && !ZeroSecondOpOnly) {
52874     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnes()) ||
52875         (IsSub && CC == X86::COND_B && ConstantX->isZero())) {
52876       // This is a complicated way to get -1 or 0 from the carry flag:
52877       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
52878       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
52879       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
52880                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
52881                          EFLAGS);
52882     }
52883 
52884     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnes()) ||
52885         (IsSub && CC == X86::COND_A && ConstantX->isZero())) {
52886       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
52887           EFLAGS.getValueType().isInteger() &&
52888           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
52889         // Swap the operands of a SUB, and we have the same pattern as above.
52890         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
52891         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
52892         SDValue NewSub = DAG.getNode(
52893             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
52894             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
52895         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
52896         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
52897                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
52898                            NewEFLAGS);
52899       }
52900     }
52901   }
52902 
52903   if (CC == X86::COND_B) {
52904     // X + SETB Z --> adc X, 0
52905     // X - SETB Z --> sbb X, 0
52906     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
52907                        DAG.getVTList(VT, MVT::i32), X,
52908                        DAG.getConstant(0, DL, VT), EFLAGS);
52909   }
52910 
52911   if (ZeroSecondOpOnly)
52912     return SDValue();
52913 
52914   if (CC == X86::COND_A) {
52915     // Try to convert COND_A into COND_B in an attempt to facilitate
52916     // materializing "setb reg".
52917     //
52918     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
52919     // cannot take an immediate as its first operand.
52920     //
52921     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
52922         EFLAGS.getValueType().isInteger() &&
52923         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
52924       SDValue NewSub =
52925           DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
52926                       EFLAGS.getOperand(1), EFLAGS.getOperand(0));
52927       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
52928       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
52929                          DAG.getVTList(VT, MVT::i32), X,
52930                          DAG.getConstant(0, DL, VT), NewEFLAGS);
52931     }
52932   }
52933 
52934   if (CC == X86::COND_AE) {
52935     // X + SETAE --> sbb X, -1
52936     // X - SETAE --> adc X, -1
52937     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
52938                        DAG.getVTList(VT, MVT::i32), X,
52939                        DAG.getConstant(-1, DL, VT), EFLAGS);
52940   }
52941 
52942   if (CC == X86::COND_BE) {
52943     // X + SETBE --> sbb X, -1
52944     // X - SETBE --> adc X, -1
52945     // Try to convert COND_BE into COND_AE in an attempt to facilitate
52946     // materializing "setae reg".
52947     //
52948     // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
52949     // cannot take an immediate as its first operand.
52950     //
52951     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
52952         EFLAGS.getValueType().isInteger() &&
52953         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
52954       SDValue NewSub =
52955           DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
52956                       EFLAGS.getOperand(1), EFLAGS.getOperand(0));
52957       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
52958       return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
52959                          DAG.getVTList(VT, MVT::i32), X,
52960                          DAG.getConstant(-1, DL, VT), NewEFLAGS);
52961     }
52962   }
52963 
52964   if (CC != X86::COND_E && CC != X86::COND_NE)
52965     return SDValue();
52966 
52967   if (EFLAGS.getOpcode() != X86ISD::CMP || !EFLAGS.hasOneUse() ||
52968       !X86::isZeroNode(EFLAGS.getOperand(1)) ||
52969       !EFLAGS.getOperand(0).getValueType().isInteger())
52970     return SDValue();
52971 
52972   SDValue Z = EFLAGS.getOperand(0);
52973   EVT ZVT = Z.getValueType();
52974 
52975   // If X is -1 or 0, then we have an opportunity to avoid constants required in
52976   // the general case below.
52977   if (ConstantX) {
52978     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
52979     // fake operands:
52980     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
52981     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
52982     if ((IsSub && CC == X86::COND_NE && ConstantX->isZero()) ||
52983         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnes())) {
52984       SDValue Zero = DAG.getConstant(0, DL, ZVT);
52985       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
52986       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
52987       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
52988                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
52989                          SDValue(Neg.getNode(), 1));
52990     }
52991 
52992     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
52993     // with fake operands:
52994     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
52995     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
52996     if ((IsSub && CC == X86::COND_E && ConstantX->isZero()) ||
52997         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnes())) {
52998       SDValue One = DAG.getConstant(1, DL, ZVT);
52999       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
53000       SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
53001       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
53002                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
53003                          Cmp1.getValue(1));
53004     }
53005   }
53006 
53007   // (cmp Z, 1) sets the carry flag if Z is 0.
53008   SDValue One = DAG.getConstant(1, DL, ZVT);
53009   SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
53010   SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
53011 
53012   // Add the flags type for ADC/SBB nodes.
53013   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
53014 
53015   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
53016   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
53017   if (CC == X86::COND_NE)
53018     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
53019                        DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
53020 
53021   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
53022   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
53023   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
53024                      DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
53025 }
53026 
53027 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
53028 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
53029 /// with CMP+{ADC, SBB}.
53030 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
53031   bool IsSub = N->getOpcode() == ISD::SUB;
53032   SDValue X = N->getOperand(0);
53033   SDValue Y = N->getOperand(1);
53034   EVT VT = N->getValueType(0);
53035   SDLoc DL(N);
53036 
53037   if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, X, Y, DAG))
53038     return ADCOrSBB;
53039 
53040   // Commute and try again (negate the result for subtracts).
53041   if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, Y, X, DAG)) {
53042     if (IsSub)
53043       ADCOrSBB =
53044           DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), ADCOrSBB);
53045     return ADCOrSBB;
53046   }
53047 
53048   return SDValue();
53049 }
53050 
53051 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
53052   // Only handle test patterns.
53053   if (!isNullConstant(N->getOperand(1)))
53054     return SDValue();
53055 
53056   // If we have a CMP of a truncated binop, see if we can make a smaller binop
53057   // and use its flags directly.
53058   // TODO: Maybe we should try promoting compares that only use the zero flag
53059   // first if we can prove the upper bits with computeKnownBits?
53060   SDLoc dl(N);
53061   SDValue Op = N->getOperand(0);
53062   EVT VT = Op.getValueType();
53063 
53064   // If we have a constant logical shift that's only used in a comparison
53065   // against zero turn it into an equivalent AND. This allows turning it into
53066   // a TEST instruction later.
53067   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
53068       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
53069       onlyZeroFlagUsed(SDValue(N, 0))) {
53070     unsigned BitWidth = VT.getSizeInBits();
53071     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
53072     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
53073       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
53074       APInt Mask = Op.getOpcode() == ISD::SRL
53075                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
53076                        : APInt::getLowBitsSet(BitWidth, MaskBits);
53077       if (Mask.isSignedIntN(32)) {
53078         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
53079                          DAG.getConstant(Mask, dl, VT));
53080         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53081                            DAG.getConstant(0, dl, VT));
53082       }
53083     }
53084   }
53085 
53086   // Peek through any zero-extend if we're only testing for a zero result.
53087   if (Op.getOpcode() == ISD::ZERO_EXTEND && onlyZeroFlagUsed(SDValue(N, 0))) {
53088     SDValue Src = Op.getOperand(0);
53089     EVT SrcVT = Src.getValueType();
53090     if (SrcVT.getScalarSizeInBits() >= 8 &&
53091         DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
53092       return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Src,
53093                          DAG.getConstant(0, dl, SrcVT));
53094   }
53095 
53096   // Look for a truncate.
53097   if (Op.getOpcode() != ISD::TRUNCATE)
53098     return SDValue();
53099 
53100   SDValue Trunc = Op;
53101   Op = Op.getOperand(0);
53102 
53103   // See if we can compare with zero against the truncation source,
53104   // which should help using the Z flag from many ops. Only do this for
53105   // i32 truncated op to prevent partial-reg compares of promoted ops.
53106   EVT OpVT = Op.getValueType();
53107   APInt UpperBits =
53108       APInt::getBitsSetFrom(OpVT.getSizeInBits(), VT.getSizeInBits());
53109   if (OpVT == MVT::i32 && DAG.MaskedValueIsZero(Op, UpperBits) &&
53110       onlyZeroFlagUsed(SDValue(N, 0))) {
53111     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53112                        DAG.getConstant(0, dl, OpVT));
53113   }
53114 
53115   // After this the truncate and arithmetic op must have a single use.
53116   if (!Trunc.hasOneUse() || !Op.hasOneUse())
53117       return SDValue();
53118 
53119   unsigned NewOpc;
53120   switch (Op.getOpcode()) {
53121   default: return SDValue();
53122   case ISD::AND:
53123     // Skip and with constant. We have special handling for and with immediate
53124     // during isel to generate test instructions.
53125     if (isa<ConstantSDNode>(Op.getOperand(1)))
53126       return SDValue();
53127     NewOpc = X86ISD::AND;
53128     break;
53129   case ISD::OR:  NewOpc = X86ISD::OR;  break;
53130   case ISD::XOR: NewOpc = X86ISD::XOR; break;
53131   case ISD::ADD:
53132     // If the carry or overflow flag is used, we can't truncate.
53133     if (needCarryOrOverflowFlag(SDValue(N, 0)))
53134       return SDValue();
53135     NewOpc = X86ISD::ADD;
53136     break;
53137   case ISD::SUB:
53138     // If the carry or overflow flag is used, we can't truncate.
53139     if (needCarryOrOverflowFlag(SDValue(N, 0)))
53140       return SDValue();
53141     NewOpc = X86ISD::SUB;
53142     break;
53143   }
53144 
53145   // We found an op we can narrow. Truncate its inputs.
53146   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
53147   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
53148 
53149   // Use a X86 specific opcode to avoid DAG combine messing with it.
53150   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
53151   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
53152 
53153   // For AND, keep a CMP so that we can match the test pattern.
53154   if (NewOpc == X86ISD::AND)
53155     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53156                        DAG.getConstant(0, dl, VT));
53157 
53158   // Return the flags.
53159   return Op.getValue(1);
53160 }
53161 
53162 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
53163                                 TargetLowering::DAGCombinerInfo &DCI) {
53164   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
53165          "Expected X86ISD::ADD or X86ISD::SUB");
53166 
53167   SDLoc DL(N);
53168   SDValue LHS = N->getOperand(0);
53169   SDValue RHS = N->getOperand(1);
53170   MVT VT = LHS.getSimpleValueType();
53171   bool IsSub = X86ISD::SUB == N->getOpcode();
53172   unsigned GenericOpc = IsSub ? ISD::SUB : ISD::ADD;
53173 
53174   // If we don't use the flag result, simplify back to a generic ADD/SUB.
53175   if (!N->hasAnyUseOfValue(1)) {
53176     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
53177     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
53178   }
53179 
53180   // Fold any similar generic ADD/SUB opcodes to reuse this node.
53181   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
53182     SDValue Ops[] = {N0, N1};
53183     SDVTList VTs = DAG.getVTList(N->getValueType(0));
53184     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
53185       SDValue Op(N, 0);
53186       if (Negate)
53187         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
53188       DCI.CombineTo(GenericAddSub, Op);
53189     }
53190   };
53191   MatchGeneric(LHS, RHS, false);
53192   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
53193 
53194   // TODO: Can we drop the ZeroSecondOpOnly limit? This is to guarantee that the
53195   // EFLAGS result doesn't change.
53196   return combineAddOrSubToADCOrSBB(IsSub, DL, VT, LHS, RHS, DAG,
53197                                    /*ZeroSecondOpOnly*/ true);
53198 }
53199 
53200 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
53201   SDValue LHS = N->getOperand(0);
53202   SDValue RHS = N->getOperand(1);
53203   SDValue BorrowIn = N->getOperand(2);
53204 
53205   if (SDValue Flags = combineCarryThroughADD(BorrowIn, DAG)) {
53206     MVT VT = N->getSimpleValueType(0);
53207     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
53208     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs, LHS, RHS, Flags);
53209   }
53210 
53211   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
53212   // iff the flag result is dead.
53213   if (LHS.getOpcode() == ISD::SUB && isNullConstant(RHS) &&
53214       !N->hasAnyUseOfValue(1))
53215     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), LHS.getOperand(0),
53216                        LHS.getOperand(1), BorrowIn);
53217 
53218   return SDValue();
53219 }
53220 
53221 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
53222 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
53223                           TargetLowering::DAGCombinerInfo &DCI) {
53224   SDValue LHS = N->getOperand(0);
53225   SDValue RHS = N->getOperand(1);
53226   SDValue CarryIn = N->getOperand(2);
53227   auto *LHSC = dyn_cast<ConstantSDNode>(LHS);
53228   auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
53229 
53230   // Canonicalize constant to RHS.
53231   if (LHSC && !RHSC)
53232     return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), RHS, LHS,
53233                        CarryIn);
53234 
53235   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
53236   // the result is either zero or one (depending on the input carry bit).
53237   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
53238   if (LHSC && RHSC && LHSC->isZero() && RHSC->isZero() &&
53239       // We don't have a good way to replace an EFLAGS use, so only do this when
53240       // dead right now.
53241       SDValue(N, 1).use_empty()) {
53242     SDLoc DL(N);
53243     EVT VT = N->getValueType(0);
53244     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
53245     SDValue Res1 = DAG.getNode(
53246         ISD::AND, DL, VT,
53247         DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
53248                     DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), CarryIn),
53249         DAG.getConstant(1, DL, VT));
53250     return DCI.CombineTo(N, Res1, CarryOut);
53251   }
53252 
53253   // Fold ADC(C1,C2,Carry) -> ADC(0,C1+C2,Carry)
53254   // iff the flag result is dead.
53255   // TODO: Allow flag result if C1+C2 doesn't signed/unsigned overflow.
53256   if (LHSC && RHSC && !LHSC->isZero() && !N->hasAnyUseOfValue(1)) {
53257     SDLoc DL(N);
53258     APInt Sum = LHSC->getAPIntValue() + RHSC->getAPIntValue();
53259     return DAG.getNode(X86ISD::ADC, DL, N->getVTList(),
53260                        DAG.getConstant(0, DL, LHS.getValueType()),
53261                        DAG.getConstant(Sum, DL, LHS.getValueType()), CarryIn);
53262   }
53263 
53264   if (SDValue Flags = combineCarryThroughADD(CarryIn, DAG)) {
53265     MVT VT = N->getSimpleValueType(0);
53266     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
53267     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs, LHS, RHS, Flags);
53268   }
53269 
53270   // Fold ADC(ADD(X,Y),0,Carry) -> ADC(X,Y,Carry)
53271   // iff the flag result is dead.
53272   if (LHS.getOpcode() == ISD::ADD && RHSC && RHSC->isZero() &&
53273       !N->hasAnyUseOfValue(1))
53274     return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), LHS.getOperand(0),
53275                        LHS.getOperand(1), CarryIn);
53276 
53277   return SDValue();
53278 }
53279 
53280 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
53281                             const SDLoc &DL, EVT VT,
53282                             const X86Subtarget &Subtarget) {
53283   // Example of pattern we try to detect:
53284   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
53285   //(add (build_vector (extract_elt t, 0),
53286   //                   (extract_elt t, 2),
53287   //                   (extract_elt t, 4),
53288   //                   (extract_elt t, 6)),
53289   //     (build_vector (extract_elt t, 1),
53290   //                   (extract_elt t, 3),
53291   //                   (extract_elt t, 5),
53292   //                   (extract_elt t, 7)))
53293 
53294   if (!Subtarget.hasSSE2())
53295     return SDValue();
53296 
53297   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
53298       Op1.getOpcode() != ISD::BUILD_VECTOR)
53299     return SDValue();
53300 
53301   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
53302       VT.getVectorNumElements() < 4 ||
53303       !isPowerOf2_32(VT.getVectorNumElements()))
53304     return SDValue();
53305 
53306   // Check if one of Op0,Op1 is of the form:
53307   // (build_vector (extract_elt Mul, 0),
53308   //               (extract_elt Mul, 2),
53309   //               (extract_elt Mul, 4),
53310   //                   ...
53311   // the other is of the form:
53312   // (build_vector (extract_elt Mul, 1),
53313   //               (extract_elt Mul, 3),
53314   //               (extract_elt Mul, 5),
53315   //                   ...
53316   // and identify Mul.
53317   SDValue Mul;
53318   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
53319     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
53320             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
53321     // TODO: Be more tolerant to undefs.
53322     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53323         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53324         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53325         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
53326       return SDValue();
53327     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
53328     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
53329     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
53330     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
53331     if (!Const0L || !Const1L || !Const0H || !Const1H)
53332       return SDValue();
53333     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
53334              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
53335     // Commutativity of mul allows factors of a product to reorder.
53336     if (Idx0L > Idx1L)
53337       std::swap(Idx0L, Idx1L);
53338     if (Idx0H > Idx1H)
53339       std::swap(Idx0H, Idx1H);
53340     // Commutativity of add allows pairs of factors to reorder.
53341     if (Idx0L > Idx0H) {
53342       std::swap(Idx0L, Idx0H);
53343       std::swap(Idx1L, Idx1H);
53344     }
53345     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
53346         Idx1H != 2 * i + 3)
53347       return SDValue();
53348     if (!Mul) {
53349       // First time an extract_elt's source vector is visited. Must be a MUL
53350       // with 2X number of vector elements than the BUILD_VECTOR.
53351       // Both extracts must be from same MUL.
53352       Mul = Op0L->getOperand(0);
53353       if (Mul->getOpcode() != ISD::MUL ||
53354           Mul.getValueType().getVectorNumElements() != 2 * e)
53355         return SDValue();
53356     }
53357     // Check that the extract is from the same MUL previously seen.
53358     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
53359         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
53360       return SDValue();
53361   }
53362 
53363   // Check if the Mul source can be safely shrunk.
53364   ShrinkMode Mode;
53365   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
53366       Mode == ShrinkMode::MULU16)
53367     return SDValue();
53368 
53369   EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53370                                  VT.getVectorNumElements() * 2);
53371   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
53372   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
53373 
53374   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
53375                          ArrayRef<SDValue> Ops) {
53376     EVT InVT = Ops[0].getValueType();
53377     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
53378     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
53379                                  InVT.getVectorNumElements() / 2);
53380     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
53381   };
53382   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
53383 }
53384 
53385 // Attempt to turn this pattern into PMADDWD.
53386 // (add (mul (sext (build_vector)), (sext (build_vector))),
53387 //      (mul (sext (build_vector)), (sext (build_vector)))
53388 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
53389                               const SDLoc &DL, EVT VT,
53390                               const X86Subtarget &Subtarget) {
53391   if (!Subtarget.hasSSE2())
53392     return SDValue();
53393 
53394   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
53395     return SDValue();
53396 
53397   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
53398       VT.getVectorNumElements() < 4 ||
53399       !isPowerOf2_32(VT.getVectorNumElements()))
53400     return SDValue();
53401 
53402   SDValue N00 = N0.getOperand(0);
53403   SDValue N01 = N0.getOperand(1);
53404   SDValue N10 = N1.getOperand(0);
53405   SDValue N11 = N1.getOperand(1);
53406 
53407   // All inputs need to be sign extends.
53408   // TODO: Support ZERO_EXTEND from known positive?
53409   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
53410       N01.getOpcode() != ISD::SIGN_EXTEND ||
53411       N10.getOpcode() != ISD::SIGN_EXTEND ||
53412       N11.getOpcode() != ISD::SIGN_EXTEND)
53413     return SDValue();
53414 
53415   // Peek through the extends.
53416   N00 = N00.getOperand(0);
53417   N01 = N01.getOperand(0);
53418   N10 = N10.getOperand(0);
53419   N11 = N11.getOperand(0);
53420 
53421   // Must be extending from vXi16.
53422   EVT InVT = N00.getValueType();
53423   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
53424       N10.getValueType() != InVT || N11.getValueType() != InVT)
53425     return SDValue();
53426 
53427   // All inputs should be build_vectors.
53428   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
53429       N01.getOpcode() != ISD::BUILD_VECTOR ||
53430       N10.getOpcode() != ISD::BUILD_VECTOR ||
53431       N11.getOpcode() != ISD::BUILD_VECTOR)
53432     return SDValue();
53433 
53434   // For each element, we need to ensure we have an odd element from one vector
53435   // multiplied by the odd element of another vector and the even element from
53436   // one of the same vectors being multiplied by the even element from the
53437   // other vector. So we need to make sure for each element i, this operator
53438   // is being performed:
53439   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
53440   SDValue In0, In1;
53441   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
53442     SDValue N00Elt = N00.getOperand(i);
53443     SDValue N01Elt = N01.getOperand(i);
53444     SDValue N10Elt = N10.getOperand(i);
53445     SDValue N11Elt = N11.getOperand(i);
53446     // TODO: Be more tolerant to undefs.
53447     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53448         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53449         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53450         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
53451       return SDValue();
53452     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
53453     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
53454     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
53455     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
53456     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
53457       return SDValue();
53458     unsigned IdxN00 = ConstN00Elt->getZExtValue();
53459     unsigned IdxN01 = ConstN01Elt->getZExtValue();
53460     unsigned IdxN10 = ConstN10Elt->getZExtValue();
53461     unsigned IdxN11 = ConstN11Elt->getZExtValue();
53462     // Add is commutative so indices can be reordered.
53463     if (IdxN00 > IdxN10) {
53464       std::swap(IdxN00, IdxN10);
53465       std::swap(IdxN01, IdxN11);
53466     }
53467     // N0 indices be the even element. N1 indices must be the next odd element.
53468     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
53469         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
53470       return SDValue();
53471     SDValue N00In = N00Elt.getOperand(0);
53472     SDValue N01In = N01Elt.getOperand(0);
53473     SDValue N10In = N10Elt.getOperand(0);
53474     SDValue N11In = N11Elt.getOperand(0);
53475 
53476     // First time we find an input capture it.
53477     if (!In0) {
53478       In0 = N00In;
53479       In1 = N01In;
53480 
53481       // The input vectors must be at least as wide as the output.
53482       // If they are larger than the output, we extract subvector below.
53483       if (In0.getValueSizeInBits() < VT.getSizeInBits() ||
53484           In1.getValueSizeInBits() < VT.getSizeInBits())
53485         return SDValue();
53486     }
53487     // Mul is commutative so the input vectors can be in any order.
53488     // Canonicalize to make the compares easier.
53489     if (In0 != N00In)
53490       std::swap(N00In, N01In);
53491     if (In0 != N10In)
53492       std::swap(N10In, N11In);
53493     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
53494       return SDValue();
53495   }
53496 
53497   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
53498                          ArrayRef<SDValue> Ops) {
53499     EVT OpVT = Ops[0].getValueType();
53500     assert(OpVT.getScalarType() == MVT::i16 &&
53501            "Unexpected scalar element type");
53502     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
53503     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
53504                                  OpVT.getVectorNumElements() / 2);
53505     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
53506   };
53507 
53508   // If the output is narrower than an input, extract the low part of the input
53509   // vector.
53510   EVT OutVT16 = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53511                                VT.getVectorNumElements() * 2);
53512   if (OutVT16.bitsLT(In0.getValueType())) {
53513     In0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In0,
53514                       DAG.getIntPtrConstant(0, DL));
53515   }
53516   if (OutVT16.bitsLT(In1.getValueType())) {
53517     In1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In1,
53518                       DAG.getIntPtrConstant(0, DL));
53519   }
53520   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
53521                           PMADDBuilder);
53522 }
53523 
53524 // ADD(VPMADDWD(X,Y),VPMADDWD(Z,W)) -> VPMADDWD(SHUFFLE(X,Z), SHUFFLE(Y,W))
53525 // If upper element in each pair of both VPMADDWD are zero then we can merge
53526 // the operand elements and use the implicit add of VPMADDWD.
53527 // TODO: Add support for VPMADDUBSW (which isn't commutable).
53528 static SDValue combineAddOfPMADDWD(SelectionDAG &DAG, SDValue N0, SDValue N1,
53529                                    const SDLoc &DL, EVT VT) {
53530   if (N0.getOpcode() != N1.getOpcode() || N0.getOpcode() != X86ISD::VPMADDWD)
53531     return SDValue();
53532 
53533   // TODO: Add 256/512-bit support once VPMADDWD combines with shuffles.
53534   if (VT.getSizeInBits() > 128)
53535     return SDValue();
53536 
53537   unsigned NumElts = VT.getVectorNumElements();
53538   MVT OpVT = N0.getOperand(0).getSimpleValueType();
53539   APInt DemandedBits = APInt::getAllOnes(OpVT.getScalarSizeInBits());
53540   APInt DemandedHiElts = APInt::getSplat(2 * NumElts, APInt(2, 2));
53541 
53542   bool Op0HiZero =
53543       DAG.MaskedValueIsZero(N0.getOperand(0), DemandedBits, DemandedHiElts) ||
53544       DAG.MaskedValueIsZero(N0.getOperand(1), DemandedBits, DemandedHiElts);
53545   bool Op1HiZero =
53546       DAG.MaskedValueIsZero(N1.getOperand(0), DemandedBits, DemandedHiElts) ||
53547       DAG.MaskedValueIsZero(N1.getOperand(1), DemandedBits, DemandedHiElts);
53548 
53549   // TODO: Check for zero lower elements once we have actual codegen that
53550   // creates them.
53551   if (!Op0HiZero || !Op1HiZero)
53552     return SDValue();
53553 
53554   // Create a shuffle mask packing the lower elements from each VPMADDWD.
53555   SmallVector<int> Mask;
53556   for (int i = 0; i != (int)NumElts; ++i) {
53557     Mask.push_back(2 * i);
53558     Mask.push_back(2 * (i + NumElts));
53559   }
53560 
53561   SDValue LHS =
53562       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(0), N1.getOperand(0), Mask);
53563   SDValue RHS =
53564       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(1), N1.getOperand(1), Mask);
53565   return DAG.getNode(X86ISD::VPMADDWD, DL, VT, LHS, RHS);
53566 }
53567 
53568 /// CMOV of constants requires materializing constant operands in registers.
53569 /// Try to fold those constants into an 'add' instruction to reduce instruction
53570 /// count. We do this with CMOV rather the generic 'select' because there are
53571 /// earlier folds that may be used to turn select-of-constants into logic hacks.
53572 static SDValue pushAddIntoCmovOfConsts(SDNode *N, SelectionDAG &DAG,
53573                                        const X86Subtarget &Subtarget) {
53574   // If an operand is zero, add-of-0 gets simplified away, so that's clearly
53575   // better because we eliminate 1-2 instructions. This transform is still
53576   // an improvement without zero operands because we trade 2 move constants and
53577   // 1 add for 2 adds (LEA) as long as the constants can be represented as
53578   // immediate asm operands (fit in 32-bits).
53579   auto isSuitableCmov = [](SDValue V) {
53580     if (V.getOpcode() != X86ISD::CMOV || !V.hasOneUse())
53581       return false;
53582     if (!isa<ConstantSDNode>(V.getOperand(0)) ||
53583         !isa<ConstantSDNode>(V.getOperand(1)))
53584       return false;
53585     return isNullConstant(V.getOperand(0)) || isNullConstant(V.getOperand(1)) ||
53586            (V.getConstantOperandAPInt(0).isSignedIntN(32) &&
53587             V.getConstantOperandAPInt(1).isSignedIntN(32));
53588   };
53589 
53590   // Match an appropriate CMOV as the first operand of the add.
53591   SDValue Cmov = N->getOperand(0);
53592   SDValue OtherOp = N->getOperand(1);
53593   if (!isSuitableCmov(Cmov))
53594     std::swap(Cmov, OtherOp);
53595   if (!isSuitableCmov(Cmov))
53596     return SDValue();
53597 
53598   // Don't remove a load folding opportunity for the add. That would neutralize
53599   // any improvements from removing constant materializations.
53600   if (X86::mayFoldLoad(OtherOp, Subtarget))
53601     return SDValue();
53602 
53603   EVT VT = N->getValueType(0);
53604   SDLoc DL(N);
53605   SDValue FalseOp = Cmov.getOperand(0);
53606   SDValue TrueOp = Cmov.getOperand(1);
53607 
53608   // We will push the add through the select, but we can potentially do better
53609   // if we know there is another add in the sequence and this is pointer math.
53610   // In that case, we can absorb an add into the trailing memory op and avoid
53611   // a 3-operand LEA which is likely slower than a 2-operand LEA.
53612   // TODO: If target has "slow3OpsLEA", do this even without the trailing memop?
53613   if (OtherOp.getOpcode() == ISD::ADD && OtherOp.hasOneUse() &&
53614       !isa<ConstantSDNode>(OtherOp.getOperand(0)) &&
53615       all_of(N->uses(), [&](SDNode *Use) {
53616         auto *MemNode = dyn_cast<MemSDNode>(Use);
53617         return MemNode && MemNode->getBasePtr().getNode() == N;
53618       })) {
53619     // add (cmov C1, C2), add (X, Y) --> add (cmov (add X, C1), (add X, C2)), Y
53620     // TODO: We are arbitrarily choosing op0 as the 1st piece of the sum, but
53621     //       it is possible that choosing op1 might be better.
53622     SDValue X = OtherOp.getOperand(0), Y = OtherOp.getOperand(1);
53623     FalseOp = DAG.getNode(ISD::ADD, DL, VT, X, FalseOp);
53624     TrueOp = DAG.getNode(ISD::ADD, DL, VT, X, TrueOp);
53625     Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp,
53626                        Cmov.getOperand(2), Cmov.getOperand(3));
53627     return DAG.getNode(ISD::ADD, DL, VT, Cmov, Y);
53628   }
53629 
53630   // add (cmov C1, C2), OtherOp --> cmov (add OtherOp, C1), (add OtherOp, C2)
53631   FalseOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, FalseOp);
53632   TrueOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, TrueOp);
53633   return DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp, Cmov.getOperand(2),
53634                      Cmov.getOperand(3));
53635 }
53636 
53637 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
53638                           TargetLowering::DAGCombinerInfo &DCI,
53639                           const X86Subtarget &Subtarget) {
53640   EVT VT = N->getValueType(0);
53641   SDValue Op0 = N->getOperand(0);
53642   SDValue Op1 = N->getOperand(1);
53643   SDLoc DL(N);
53644 
53645   if (SDValue Select = pushAddIntoCmovOfConsts(N, DAG, Subtarget))
53646     return Select;
53647 
53648   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, DL, VT, Subtarget))
53649     return MAdd;
53650   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, DL, VT, Subtarget))
53651     return MAdd;
53652   if (SDValue MAdd = combineAddOfPMADDWD(DAG, Op0, Op1, DL, VT))
53653     return MAdd;
53654 
53655   // Try to synthesize horizontal adds from adds of shuffles.
53656   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
53657     return V;
53658 
53659   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
53660   // (sub Y, (sext (vXi1 X))).
53661   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
53662   // generic DAG combine without a legal type check, but adding this there
53663   // caused regressions.
53664   if (VT.isVector()) {
53665     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53666     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
53667         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
53668         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
53669       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
53670       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
53671     }
53672 
53673     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
53674         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
53675         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
53676       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
53677       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
53678     }
53679   }
53680 
53681   // Fold ADD(ADC(Y,0,W),X) -> ADC(X,Y,W)
53682   if (Op0.getOpcode() == X86ISD::ADC && Op0->hasOneUse() &&
53683       X86::isZeroNode(Op0.getOperand(1))) {
53684     assert(!Op0->hasAnyUseOfValue(1) && "Overflow bit in use");
53685     return DAG.getNode(X86ISD::ADC, SDLoc(Op0), Op0->getVTList(), Op1,
53686                        Op0.getOperand(0), Op0.getOperand(2));
53687   }
53688 
53689   return combineAddOrSubToADCOrSBB(N, DAG);
53690 }
53691 
53692 // Try to fold (sub Y, cmovns X, -X) -> (add Y, cmovns -X, X) if the cmov
53693 // condition comes from the subtract node that produced -X. This matches the
53694 // cmov expansion for absolute value. By swapping the operands we convert abs
53695 // to nabs.
53696 static SDValue combineSubABS(SDNode *N, SelectionDAG &DAG) {
53697   SDValue N0 = N->getOperand(0);
53698   SDValue N1 = N->getOperand(1);
53699 
53700   if (N1.getOpcode() != X86ISD::CMOV || !N1.hasOneUse())
53701     return SDValue();
53702 
53703   X86::CondCode CC = (X86::CondCode)N1.getConstantOperandVal(2);
53704   if (CC != X86::COND_S && CC != X86::COND_NS)
53705     return SDValue();
53706 
53707   // Condition should come from a negate operation.
53708   SDValue Cond = N1.getOperand(3);
53709   if (Cond.getOpcode() != X86ISD::SUB || !isNullConstant(Cond.getOperand(0)))
53710     return SDValue();
53711   assert(Cond.getResNo() == 1 && "Unexpected result number");
53712 
53713   // Get the X and -X from the negate.
53714   SDValue NegX = Cond.getValue(0);
53715   SDValue X = Cond.getOperand(1);
53716 
53717   SDValue FalseOp = N1.getOperand(0);
53718   SDValue TrueOp = N1.getOperand(1);
53719 
53720   // Cmov operands should be X and NegX. Order doesn't matter.
53721   if (!(TrueOp == X && FalseOp == NegX) && !(TrueOp == NegX && FalseOp == X))
53722     return SDValue();
53723 
53724   // Build a new CMOV with the operands swapped.
53725   SDLoc DL(N);
53726   MVT VT = N->getSimpleValueType(0);
53727   SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, TrueOp, FalseOp,
53728                              N1.getOperand(2), Cond);
53729   // Convert sub to add.
53730   return DAG.getNode(ISD::ADD, DL, VT, N0, Cmov);
53731 }
53732 
53733 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
53734                           TargetLowering::DAGCombinerInfo &DCI,
53735                           const X86Subtarget &Subtarget) {
53736   SDValue Op0 = N->getOperand(0);
53737   SDValue Op1 = N->getOperand(1);
53738 
53739   // TODO: Add NoOpaque handling to isConstantIntBuildVectorOrConstantInt.
53740   auto IsNonOpaqueConstant = [&](SDValue Op) {
53741     if (SDNode *C = DAG.isConstantIntBuildVectorOrConstantInt(Op)) {
53742       if (auto *Cst = dyn_cast<ConstantSDNode>(C))
53743         return !Cst->isOpaque();
53744       return true;
53745     }
53746     return false;
53747   };
53748 
53749   // X86 can't encode an immediate LHS of a sub. See if we can push the
53750   // negation into a preceding instruction. If the RHS of the sub is a XOR with
53751   // one use and a constant, invert the immediate, saving one register.
53752   // sub(C1, xor(X, C2)) -> add(xor(X, ~C2), C1+1)
53753   if (Op1.getOpcode() == ISD::XOR && IsNonOpaqueConstant(Op0) &&
53754       IsNonOpaqueConstant(Op1.getOperand(1)) && Op1->hasOneUse()) {
53755     SDLoc DL(N);
53756     EVT VT = Op0.getValueType();
53757     SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, Op1.getOperand(0),
53758                                  DAG.getNOT(SDLoc(Op1), Op1.getOperand(1), VT));
53759     SDValue NewAdd =
53760         DAG.getNode(ISD::ADD, DL, VT, Op0, DAG.getConstant(1, DL, VT));
53761     return DAG.getNode(ISD::ADD, DL, VT, NewXor, NewAdd);
53762   }
53763 
53764   if (SDValue V = combineSubABS(N, DAG))
53765     return V;
53766 
53767   // Try to synthesize horizontal subs from subs of shuffles.
53768   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
53769     return V;
53770 
53771   // Fold SUB(X,ADC(Y,0,W)) -> SBB(X,Y,W)
53772   if (Op1.getOpcode() == X86ISD::ADC && Op1->hasOneUse() &&
53773       X86::isZeroNode(Op1.getOperand(1))) {
53774     assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
53775     return DAG.getNode(X86ISD::SBB, SDLoc(Op1), Op1->getVTList(), Op0,
53776                        Op1.getOperand(0), Op1.getOperand(2));
53777   }
53778 
53779   // Fold SUB(X,SBB(Y,Z,W)) -> SUB(ADC(X,Z,W),Y)
53780   // Don't fold to ADC(0,0,W)/SETCC_CARRY pattern which will prevent more folds.
53781   if (Op1.getOpcode() == X86ISD::SBB && Op1->hasOneUse() &&
53782       !(X86::isZeroNode(Op0) && X86::isZeroNode(Op1.getOperand(1)))) {
53783     assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
53784     SDValue ADC = DAG.getNode(X86ISD::ADC, SDLoc(Op1), Op1->getVTList(), Op0,
53785                               Op1.getOperand(1), Op1.getOperand(2));
53786     return DAG.getNode(ISD::SUB, SDLoc(N), Op0.getValueType(), ADC.getValue(0),
53787                        Op1.getOperand(0));
53788   }
53789 
53790   return combineAddOrSubToADCOrSBB(N, DAG);
53791 }
53792 
53793 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
53794                                     const X86Subtarget &Subtarget) {
53795   MVT VT = N->getSimpleValueType(0);
53796   SDLoc DL(N);
53797 
53798   if (N->getOperand(0) == N->getOperand(1)) {
53799     if (N->getOpcode() == X86ISD::PCMPEQ)
53800       return DAG.getConstant(-1, DL, VT);
53801     if (N->getOpcode() == X86ISD::PCMPGT)
53802       return DAG.getConstant(0, DL, VT);
53803   }
53804 
53805   return SDValue();
53806 }
53807 
53808 /// Helper that combines an array of subvector ops as if they were the operands
53809 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
53810 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
53811 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
53812                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
53813                                       TargetLowering::DAGCombinerInfo &DCI,
53814                                       const X86Subtarget &Subtarget) {
53815   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
53816   unsigned EltSizeInBits = VT.getScalarSizeInBits();
53817 
53818   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
53819     return DAG.getUNDEF(VT);
53820 
53821   if (llvm::all_of(Ops, [](SDValue Op) {
53822         return ISD::isBuildVectorAllZeros(Op.getNode());
53823       }))
53824     return getZeroVector(VT, Subtarget, DAG, DL);
53825 
53826   SDValue Op0 = Ops[0];
53827   bool IsSplat = llvm::all_of(Ops, [&Op0](SDValue Op) { return Op == Op0; });
53828 
53829   // Repeated subvectors.
53830   if (IsSplat &&
53831       (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
53832     // If this broadcast is inserted into both halves, use a larger broadcast.
53833     if (Op0.getOpcode() == X86ISD::VBROADCAST)
53834       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
53835 
53836     // If this simple subvector or scalar/subvector broadcast_load is inserted
53837     // into both halves, use a larger broadcast_load. Update other uses to use
53838     // an extracted subvector.
53839     if (ISD::isNormalLoad(Op0.getNode()) ||
53840         Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
53841         Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
53842       auto *Mem = cast<MemSDNode>(Op0);
53843       unsigned Opc = Op0.getOpcode() == X86ISD::VBROADCAST_LOAD
53844                          ? X86ISD::VBROADCAST_LOAD
53845                          : X86ISD::SUBV_BROADCAST_LOAD;
53846       if (SDValue BcastLd =
53847               getBROADCAST_LOAD(Opc, DL, VT, Mem->getMemoryVT(), Mem, 0, DAG)) {
53848         SDValue BcastSrc =
53849             extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits());
53850         DAG.ReplaceAllUsesOfValueWith(Op0, BcastSrc);
53851         return BcastLd;
53852       }
53853     }
53854 
53855     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
53856     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
53857         (Subtarget.hasAVX2() ||
53858          X86::mayFoldLoadIntoBroadcastFromMem(Op0.getOperand(0),
53859                                               VT.getScalarType(), Subtarget)))
53860       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
53861                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
53862                                      Op0.getOperand(0),
53863                                      DAG.getIntPtrConstant(0, DL)));
53864 
53865     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
53866     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
53867         (Subtarget.hasAVX2() ||
53868          (EltSizeInBits >= 32 &&
53869           X86::mayFoldLoad(Op0.getOperand(0), Subtarget))) &&
53870         Op0.getOperand(0).getValueType() == VT.getScalarType())
53871       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
53872 
53873     // concat_vectors(extract_subvector(broadcast(x)),
53874     //                extract_subvector(broadcast(x))) -> broadcast(x)
53875     if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
53876         Op0.getOperand(0).getValueType() == VT) {
53877       if (Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST ||
53878           Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST_LOAD)
53879         return Op0.getOperand(0);
53880     }
53881   }
53882 
53883   // concat(extract_subvector(v0,c0), extract_subvector(v1,c1)) -> vperm2x128.
53884   // Only concat of subvector high halves which vperm2x128 is best at.
53885   // TODO: This should go in combineX86ShufflesRecursively eventually.
53886   if (VT.is256BitVector() && Ops.size() == 2) {
53887     SDValue Src0 = peekThroughBitcasts(Ops[0]);
53888     SDValue Src1 = peekThroughBitcasts(Ops[1]);
53889     if (Src0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
53890         Src1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
53891       EVT SrcVT0 = Src0.getOperand(0).getValueType();
53892       EVT SrcVT1 = Src1.getOperand(0).getValueType();
53893       unsigned NumSrcElts0 = SrcVT0.getVectorNumElements();
53894       unsigned NumSrcElts1 = SrcVT1.getVectorNumElements();
53895       if (SrcVT0.is256BitVector() && SrcVT1.is256BitVector() &&
53896           Src0.getConstantOperandAPInt(1) == (NumSrcElts0 / 2) &&
53897           Src1.getConstantOperandAPInt(1) == (NumSrcElts1 / 2)) {
53898         return DAG.getNode(X86ISD::VPERM2X128, DL, VT,
53899                            DAG.getBitcast(VT, Src0.getOperand(0)),
53900                            DAG.getBitcast(VT, Src1.getOperand(0)),
53901                            DAG.getTargetConstant(0x31, DL, MVT::i8));
53902       }
53903     }
53904   }
53905 
53906   // Repeated opcode.
53907   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
53908   // but it currently struggles with different vector widths.
53909   if (llvm::all_of(Ops, [Op0](SDValue Op) {
53910         return Op.getOpcode() == Op0.getOpcode();
53911       })) {
53912     auto ConcatSubOperand = [&](MVT VT, ArrayRef<SDValue> SubOps, unsigned I) {
53913       SmallVector<SDValue> Subs;
53914       for (SDValue SubOp : SubOps)
53915         Subs.push_back(SubOp.getOperand(I));
53916       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
53917     };
53918     auto IsConcatFree = [](MVT VT, ArrayRef<SDValue> SubOps, unsigned Op) {
53919       for (unsigned I = 0, E = SubOps.size(); I != E; ++I) {
53920         SDValue Sub = SubOps[I].getOperand(Op);
53921         unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
53922         if (Sub.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
53923             Sub.getOperand(0).getValueType() != VT ||
53924             Sub.getConstantOperandAPInt(1) != (I * NumSubElts))
53925           return false;
53926       }
53927       return true;
53928     };
53929 
53930     unsigned NumOps = Ops.size();
53931     switch (Op0.getOpcode()) {
53932     case X86ISD::VBROADCAST: {
53933       if (!IsSplat && VT == MVT::v4f64 && llvm::all_of(Ops, [](SDValue Op) {
53934             return Op.getOperand(0).getValueType().is128BitVector();
53935           }))
53936         return DAG.getNode(X86ISD::MOVDDUP, DL, VT,
53937                            ConcatSubOperand(VT, Ops, 0));
53938       break;
53939     }
53940     case X86ISD::MOVDDUP:
53941     case X86ISD::MOVSHDUP:
53942     case X86ISD::MOVSLDUP: {
53943       if (!IsSplat)
53944         return DAG.getNode(Op0.getOpcode(), DL, VT,
53945                            ConcatSubOperand(VT, Ops, 0));
53946       break;
53947     }
53948     case X86ISD::SHUFP: {
53949       // Add SHUFPD support if/when necessary.
53950       if (!IsSplat && VT.getScalarType() == MVT::f32 &&
53951           llvm::all_of(Ops, [Op0](SDValue Op) {
53952             return Op.getOperand(2) == Op0.getOperand(2);
53953           })) {
53954         return DAG.getNode(Op0.getOpcode(), DL, VT,
53955                            ConcatSubOperand(VT, Ops, 0),
53956                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
53957       }
53958       break;
53959     }
53960     case X86ISD::PSHUFHW:
53961     case X86ISD::PSHUFLW:
53962     case X86ISD::PSHUFD:
53963       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
53964           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
53965         return DAG.getNode(Op0.getOpcode(), DL, VT,
53966                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
53967       }
53968       LLVM_FALLTHROUGH;
53969     case X86ISD::VPERMILPI:
53970       if (!IsSplat && NumOps == 2 && (VT == MVT::v8f32 || VT == MVT::v8i32) &&
53971           Op0.getOperand(1) == Ops[1].getOperand(1)) {
53972         SDValue Res = DAG.getBitcast(MVT::v8f32, ConcatSubOperand(VT, Ops, 0));
53973         Res = DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, Res,
53974                           Op0.getOperand(1));
53975         return DAG.getBitcast(VT, Res);
53976       }
53977       if (!IsSplat && NumOps == 2 && VT == MVT::v4f64) {
53978         uint64_t Idx0 = Ops[0].getConstantOperandVal(1);
53979         uint64_t Idx1 = Ops[1].getConstantOperandVal(1);
53980         uint64_t Idx = ((Idx1 & 3) << 2) | (Idx0 & 3);
53981         return DAG.getNode(Op0.getOpcode(), DL, VT,
53982                            ConcatSubOperand(VT, Ops, 0),
53983                            DAG.getTargetConstant(Idx, DL, MVT::i8));
53984       }
53985       break;
53986     case X86ISD::PSHUFB:
53987       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
53988                        (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
53989         return DAG.getNode(Op0.getOpcode(), DL, VT,
53990                            ConcatSubOperand(VT, Ops, 0),
53991                            ConcatSubOperand(VT, Ops, 1));
53992       }
53993       break;
53994     case X86ISD::VPERMV3:
53995       if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
53996         MVT OpVT = Op0.getSimpleValueType();
53997         int NumSrcElts = OpVT.getVectorNumElements();
53998         SmallVector<int, 64> ConcatMask;
53999         for (unsigned i = 0; i != NumOps; ++i) {
54000           SmallVector<int, 64> SubMask;
54001           SmallVector<SDValue, 2> SubOps;
54002           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
54003                                     SubMask))
54004             break;
54005           for (int M : SubMask) {
54006             if (0 <= M) {
54007               M += M < NumSrcElts ? 0 : NumSrcElts;
54008               M += i * NumSrcElts;
54009             }
54010             ConcatMask.push_back(M);
54011           }
54012         }
54013         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
54014           SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
54015                                           Ops[1].getOperand(0), DAG, DL);
54016           SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
54017                                           Ops[1].getOperand(2), DAG, DL);
54018           MVT IntMaskSVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
54019           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
54020           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
54021           return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
54022         }
54023       }
54024       break;
54025     case X86ISD::VSHLI:
54026     case X86ISD::VSRLI:
54027       // Special case: SHL/SRL AVX1 V4i64 by 32-bits can lower as a shuffle.
54028       // TODO: Move this to LowerShiftByScalarImmediate?
54029       if (VT == MVT::v4i64 && !Subtarget.hasInt256() &&
54030           llvm::all_of(Ops, [](SDValue Op) {
54031             return Op.getConstantOperandAPInt(1) == 32;
54032           })) {
54033         SDValue Res = DAG.getBitcast(MVT::v8i32, ConcatSubOperand(VT, Ops, 0));
54034         SDValue Zero = getZeroVector(MVT::v8i32, Subtarget, DAG, DL);
54035         if (Op0.getOpcode() == X86ISD::VSHLI) {
54036           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
54037                                      {8, 0, 8, 2, 8, 4, 8, 6});
54038         } else {
54039           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
54040                                      {1, 8, 3, 8, 5, 8, 7, 8});
54041         }
54042         return DAG.getBitcast(VT, Res);
54043       }
54044       LLVM_FALLTHROUGH;
54045     case X86ISD::VSRAI:
54046     case X86ISD::VSHL:
54047     case X86ISD::VSRL:
54048     case X86ISD::VSRA:
54049       if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
54050            (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
54051             (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
54052           llvm::all_of(Ops, [Op0](SDValue Op) {
54053             return Op0.getOperand(1) == Op.getOperand(1);
54054           })) {
54055         return DAG.getNode(Op0.getOpcode(), DL, VT,
54056                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
54057       }
54058       break;
54059     case X86ISD::VPERMI:
54060     case X86ISD::VROTLI:
54061     case X86ISD::VROTRI:
54062       if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
54063           llvm::all_of(Ops, [Op0](SDValue Op) {
54064             return Op0.getOperand(1) == Op.getOperand(1);
54065           })) {
54066         return DAG.getNode(Op0.getOpcode(), DL, VT,
54067                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
54068       }
54069       break;
54070     case ISD::AND:
54071     case ISD::OR:
54072     case ISD::XOR:
54073     case X86ISD::ANDNP:
54074       // TODO: Add 256-bit support.
54075       if (!IsSplat && VT.is512BitVector()) {
54076         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
54077         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
54078                                  NumOps * SrcVT.getVectorNumElements());
54079         return DAG.getNode(Op0.getOpcode(), DL, VT,
54080                            ConcatSubOperand(SrcVT, Ops, 0),
54081                            ConcatSubOperand(SrcVT, Ops, 1));
54082       }
54083       break;
54084     case X86ISD::HADD:
54085     case X86ISD::HSUB:
54086     case X86ISD::FHADD:
54087     case X86ISD::FHSUB:
54088     case X86ISD::PACKSS:
54089     case X86ISD::PACKUS:
54090       if (!IsSplat && VT.is256BitVector() &&
54091           (VT.isFloatingPoint() || Subtarget.hasInt256())) {
54092         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
54093         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
54094                                  NumOps * SrcVT.getVectorNumElements());
54095         return DAG.getNode(Op0.getOpcode(), DL, VT,
54096                            ConcatSubOperand(SrcVT, Ops, 0),
54097                            ConcatSubOperand(SrcVT, Ops, 1));
54098       }
54099       break;
54100     case X86ISD::PALIGNR:
54101       if (!IsSplat &&
54102           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
54103            (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
54104           llvm::all_of(Ops, [Op0](SDValue Op) {
54105             return Op0.getOperand(2) == Op.getOperand(2);
54106           })) {
54107         return DAG.getNode(Op0.getOpcode(), DL, VT,
54108                            ConcatSubOperand(VT, Ops, 0),
54109                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
54110       }
54111       break;
54112     case ISD::VSELECT:
54113     case X86ISD::BLENDV:
54114       if (!IsSplat && VT.is256BitVector() && Ops.size() == 2 &&
54115           (VT.getScalarSizeInBits() >= 32 || Subtarget.hasInt256()) &&
54116           IsConcatFree(VT, Ops, 1) && IsConcatFree(VT, Ops, 2)) {
54117         EVT SelVT = Ops[0].getOperand(0).getValueType();
54118         SelVT = SelVT.getDoubleNumVectorElementsVT(*DAG.getContext());
54119         return DAG.getNode(Op0.getOpcode(), DL, VT,
54120                            ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
54121                            ConcatSubOperand(VT, Ops, 1),
54122                            ConcatSubOperand(VT, Ops, 2));
54123       }
54124       break;
54125     }
54126   }
54127 
54128   // Fold subvector loads into one.
54129   // If needed, look through bitcasts to get to the load.
54130   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
54131     bool Fast;
54132     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
54133     if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
54134                                 *FirstLd->getMemOperand(), &Fast) &&
54135         Fast) {
54136       if (SDValue Ld =
54137               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
54138         return Ld;
54139     }
54140   }
54141 
54142   // Attempt to fold target constant loads.
54143   if (all_of(Ops, [](SDValue Op) { return getTargetConstantFromNode(Op); })) {
54144     SmallVector<APInt> EltBits;
54145     APInt UndefElts = APInt::getNullValue(VT.getVectorNumElements());
54146     for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
54147       APInt OpUndefElts;
54148       SmallVector<APInt> OpEltBits;
54149       if (!getTargetConstantBitsFromNode(Ops[I], EltSizeInBits, OpUndefElts,
54150                                         OpEltBits, true, false))
54151           break;
54152       EltBits.append(OpEltBits);
54153       UndefElts.insertBits(OpUndefElts, I * OpUndefElts.getBitWidth());
54154     }
54155     if (EltBits.size() == VT.getVectorNumElements())
54156       return getConstVector(EltBits, UndefElts, VT, DAG, DL);
54157   }
54158 
54159   return SDValue();
54160 }
54161 
54162 static SDValue combineCONCAT_VECTORS(SDNode *N, SelectionDAG &DAG,
54163                                      TargetLowering::DAGCombinerInfo &DCI,
54164                                      const X86Subtarget &Subtarget) {
54165   EVT VT = N->getValueType(0);
54166   EVT SrcVT = N->getOperand(0).getValueType();
54167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54168 
54169   // Don't do anything for i1 vectors.
54170   if (VT.getVectorElementType() == MVT::i1)
54171     return SDValue();
54172 
54173   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
54174     SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
54175     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
54176                                            DCI, Subtarget))
54177       return R;
54178   }
54179 
54180   return SDValue();
54181 }
54182 
54183 static SDValue combineINSERT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
54184                                        TargetLowering::DAGCombinerInfo &DCI,
54185                                        const X86Subtarget &Subtarget) {
54186   if (DCI.isBeforeLegalizeOps())
54187     return SDValue();
54188 
54189   MVT OpVT = N->getSimpleValueType(0);
54190 
54191   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
54192 
54193   SDLoc dl(N);
54194   SDValue Vec = N->getOperand(0);
54195   SDValue SubVec = N->getOperand(1);
54196 
54197   uint64_t IdxVal = N->getConstantOperandVal(2);
54198   MVT SubVecVT = SubVec.getSimpleValueType();
54199 
54200   if (Vec.isUndef() && SubVec.isUndef())
54201     return DAG.getUNDEF(OpVT);
54202 
54203   // Inserting undefs/zeros into zeros/undefs is a zero vector.
54204   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
54205       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
54206     return getZeroVector(OpVT, Subtarget, DAG, dl);
54207 
54208   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
54209     // If we're inserting into a zero vector and then into a larger zero vector,
54210     // just insert into the larger zero vector directly.
54211     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
54212         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
54213       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
54214       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
54215                          getZeroVector(OpVT, Subtarget, DAG, dl),
54216                          SubVec.getOperand(1),
54217                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
54218     }
54219 
54220     // If we're inserting into a zero vector and our input was extracted from an
54221     // insert into a zero vector of the same type and the extraction was at
54222     // least as large as the original insertion. Just insert the original
54223     // subvector into a zero vector.
54224     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
54225         isNullConstant(SubVec.getOperand(1)) &&
54226         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
54227       SDValue Ins = SubVec.getOperand(0);
54228       if (isNullConstant(Ins.getOperand(2)) &&
54229           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
54230           Ins.getOperand(1).getValueSizeInBits().getFixedSize() <=
54231               SubVecVT.getFixedSizeInBits())
54232         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
54233                            getZeroVector(OpVT, Subtarget, DAG, dl),
54234                            Ins.getOperand(1), N->getOperand(2));
54235     }
54236   }
54237 
54238   // Stop here if this is an i1 vector.
54239   if (IsI1Vector)
54240     return SDValue();
54241 
54242   // If this is an insert of an extract, combine to a shuffle. Don't do this
54243   // if the insert or extract can be represented with a subregister operation.
54244   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
54245       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
54246       (IdxVal != 0 ||
54247        !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
54248     int ExtIdxVal = SubVec.getConstantOperandVal(1);
54249     if (ExtIdxVal != 0) {
54250       int VecNumElts = OpVT.getVectorNumElements();
54251       int SubVecNumElts = SubVecVT.getVectorNumElements();
54252       SmallVector<int, 64> Mask(VecNumElts);
54253       // First create an identity shuffle mask.
54254       for (int i = 0; i != VecNumElts; ++i)
54255         Mask[i] = i;
54256       // Now insert the extracted portion.
54257       for (int i = 0; i != SubVecNumElts; ++i)
54258         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
54259 
54260       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
54261     }
54262   }
54263 
54264   // Match concat_vector style patterns.
54265   SmallVector<SDValue, 2> SubVectorOps;
54266   if (collectConcatOps(N, SubVectorOps, DAG)) {
54267     if (SDValue Fold =
54268             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
54269       return Fold;
54270 
54271     // If we're inserting all zeros into the upper half, change this to
54272     // a concat with zero. We will match this to a move
54273     // with implicit upper bit zeroing during isel.
54274     // We do this here because we don't want combineConcatVectorOps to
54275     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
54276     if (SubVectorOps.size() == 2 &&
54277         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
54278       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
54279                          getZeroVector(OpVT, Subtarget, DAG, dl),
54280                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
54281   }
54282 
54283   // If this is a broadcast insert into an upper undef, use a larger broadcast.
54284   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
54285     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
54286 
54287   // If this is a broadcast load inserted into an upper undef, use a larger
54288   // broadcast load.
54289   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
54290       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
54291     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
54292     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
54293     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
54294     SDValue BcastLd =
54295         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
54296                                 MemIntr->getMemoryVT(),
54297                                 MemIntr->getMemOperand());
54298     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
54299     return BcastLd;
54300   }
54301 
54302   // If we're splatting the lower half subvector of a full vector load into the
54303   // upper half, attempt to create a subvector broadcast.
54304   if (IdxVal == (OpVT.getVectorNumElements() / 2) && SubVec.hasOneUse() &&
54305       Vec.getValueSizeInBits() == (2 * SubVec.getValueSizeInBits())) {
54306     auto *VecLd = dyn_cast<LoadSDNode>(Vec);
54307     auto *SubLd = dyn_cast<LoadSDNode>(SubVec);
54308     if (VecLd && SubLd &&
54309         DAG.areNonVolatileConsecutiveLoads(SubLd, VecLd,
54310                                            SubVec.getValueSizeInBits() / 8, 0))
54311       return getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, dl, OpVT, SubVecVT,
54312                                SubLd, 0, DAG);
54313   }
54314 
54315   return SDValue();
54316 }
54317 
54318 /// If we are extracting a subvector of a vector select and the select condition
54319 /// is composed of concatenated vectors, try to narrow the select width. This
54320 /// is a common pattern for AVX1 integer code because 256-bit selects may be
54321 /// legal, but there is almost no integer math/logic available for 256-bit.
54322 /// This function should only be called with legal types (otherwise, the calls
54323 /// to get simple value types will assert).
54324 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
54325   SDValue Sel = Ext->getOperand(0);
54326   SmallVector<SDValue, 4> CatOps;
54327   if (Sel.getOpcode() != ISD::VSELECT ||
54328       !collectConcatOps(Sel.getOperand(0).getNode(), CatOps, DAG))
54329     return SDValue();
54330 
54331   // Note: We assume simple value types because this should only be called with
54332   //       legal operations/types.
54333   // TODO: This can be extended to handle extraction to 256-bits.
54334   MVT VT = Ext->getSimpleValueType(0);
54335   if (!VT.is128BitVector())
54336     return SDValue();
54337 
54338   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
54339   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
54340     return SDValue();
54341 
54342   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
54343   MVT SelVT = Sel.getSimpleValueType();
54344   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
54345          "Unexpected vector type with legal operations");
54346 
54347   unsigned SelElts = SelVT.getVectorNumElements();
54348   unsigned CastedElts = WideVT.getVectorNumElements();
54349   unsigned ExtIdx = Ext->getConstantOperandVal(1);
54350   if (SelElts % CastedElts == 0) {
54351     // The select has the same or more (narrower) elements than the extract
54352     // operand. The extraction index gets scaled by that factor.
54353     ExtIdx *= (SelElts / CastedElts);
54354   } else if (CastedElts % SelElts == 0) {
54355     // The select has less (wider) elements than the extract operand. Make sure
54356     // that the extraction index can be divided evenly.
54357     unsigned IndexDivisor = CastedElts / SelElts;
54358     if (ExtIdx % IndexDivisor != 0)
54359       return SDValue();
54360     ExtIdx /= IndexDivisor;
54361   } else {
54362     llvm_unreachable("Element count of simple vector types are not divisible?");
54363   }
54364 
54365   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
54366   unsigned NarrowElts = SelElts / NarrowingFactor;
54367   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
54368   SDLoc DL(Ext);
54369   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
54370   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
54371   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
54372   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
54373   return DAG.getBitcast(VT, NarrowSel);
54374 }
54375 
54376 static SDValue combineEXTRACT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
54377                                         TargetLowering::DAGCombinerInfo &DCI,
54378                                         const X86Subtarget &Subtarget) {
54379   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
54380   // eventually get combined/lowered into ANDNP) with a concatenated operand,
54381   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
54382   // We let generic combining take over from there to simplify the
54383   // insert/extract and 'not'.
54384   // This pattern emerges during AVX1 legalization. We handle it before lowering
54385   // to avoid complications like splitting constant vector loads.
54386 
54387   // Capture the original wide type in the likely case that we need to bitcast
54388   // back to this type.
54389   if (!N->getValueType(0).isSimple())
54390     return SDValue();
54391 
54392   MVT VT = N->getSimpleValueType(0);
54393   SDValue InVec = N->getOperand(0);
54394   unsigned IdxVal = N->getConstantOperandVal(1);
54395   SDValue InVecBC = peekThroughBitcasts(InVec);
54396   EVT InVecVT = InVec.getValueType();
54397   unsigned SizeInBits = VT.getSizeInBits();
54398   unsigned InSizeInBits = InVecVT.getSizeInBits();
54399   unsigned NumSubElts = VT.getVectorNumElements();
54400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54401 
54402   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
54403       TLI.isTypeLegal(InVecVT) &&
54404       InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
54405     auto isConcatenatedNot = [](SDValue V) {
54406       V = peekThroughBitcasts(V);
54407       if (!isBitwiseNot(V))
54408         return false;
54409       SDValue NotOp = V->getOperand(0);
54410       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
54411     };
54412     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
54413         isConcatenatedNot(InVecBC.getOperand(1))) {
54414       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
54415       SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
54416       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
54417                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
54418     }
54419   }
54420 
54421   if (DCI.isBeforeLegalizeOps())
54422     return SDValue();
54423 
54424   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
54425     return V;
54426 
54427   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
54428     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
54429 
54430   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
54431     if (VT.getScalarType() == MVT::i1)
54432       return DAG.getConstant(1, SDLoc(N), VT);
54433     return getOnesVector(VT, DAG, SDLoc(N));
54434   }
54435 
54436   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
54437     return DAG.getBuildVector(VT, SDLoc(N),
54438                               InVec->ops().slice(IdxVal, NumSubElts));
54439 
54440   // If we are extracting from an insert into a larger vector, replace with a
54441   // smaller insert if we don't access less than the original subvector. Don't
54442   // do this for i1 vectors.
54443   // TODO: Relax the matching indices requirement?
54444   if (VT.getVectorElementType() != MVT::i1 &&
54445       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && InVec.hasOneUse() &&
54446       IdxVal == InVec.getConstantOperandVal(2) &&
54447       InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
54448     SDLoc DL(N);
54449     SDValue NewExt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT,
54450                                  InVec.getOperand(0), N->getOperand(1));
54451     unsigned NewIdxVal = InVec.getConstantOperandVal(2) - IdxVal;
54452     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, NewExt,
54453                        InVec.getOperand(1),
54454                        DAG.getVectorIdxConstant(NewIdxVal, DL));
54455   }
54456 
54457   // If we're extracting an upper subvector from a broadcast we should just
54458   // extract the lowest subvector instead which should allow
54459   // SimplifyDemandedVectorElts do more simplifications.
54460   if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
54461                       InVec.getOpcode() == X86ISD::VBROADCAST_LOAD ||
54462                       DAG.isSplatValue(InVec, /*AllowUndefs*/ false)))
54463     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
54464 
54465   // If we're extracting a broadcasted subvector, just use the lowest subvector.
54466   if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
54467       cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
54468     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
54469 
54470   // Attempt to extract from the source of a shuffle vector.
54471   if ((InSizeInBits % SizeInBits) == 0 && (IdxVal % NumSubElts) == 0) {
54472     SmallVector<int, 32> ShuffleMask;
54473     SmallVector<int, 32> ScaledMask;
54474     SmallVector<SDValue, 2> ShuffleInputs;
54475     unsigned NumSubVecs = InSizeInBits / SizeInBits;
54476     // Decode the shuffle mask and scale it so its shuffling subvectors.
54477     if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
54478         scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
54479       unsigned SubVecIdx = IdxVal / NumSubElts;
54480       if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
54481         return DAG.getUNDEF(VT);
54482       if (ScaledMask[SubVecIdx] == SM_SentinelZero)
54483         return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
54484       SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
54485       if (Src.getValueSizeInBits() == InSizeInBits) {
54486         unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
54487         unsigned SrcEltIdx = SrcSubVecIdx * NumSubElts;
54488         return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
54489                                 SDLoc(N), SizeInBits);
54490       }
54491     }
54492   }
54493 
54494   // If we're extracting the lowest subvector and we're the only user,
54495   // we may be able to perform this with a smaller vector width.
54496   unsigned InOpcode = InVec.getOpcode();
54497   if (InVec.hasOneUse()) {
54498     if (IdxVal == 0 && VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
54499       // v2f64 CVTDQ2PD(v4i32).
54500       if (InOpcode == ISD::SINT_TO_FP &&
54501           InVec.getOperand(0).getValueType() == MVT::v4i32) {
54502         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
54503       }
54504       // v2f64 CVTUDQ2PD(v4i32).
54505       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
54506           InVec.getOperand(0).getValueType() == MVT::v4i32) {
54507         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
54508       }
54509       // v2f64 CVTPS2PD(v4f32).
54510       if (InOpcode == ISD::FP_EXTEND &&
54511           InVec.getOperand(0).getValueType() == MVT::v4f32) {
54512         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
54513       }
54514     }
54515     if (IdxVal == 0 &&
54516         (InOpcode == ISD::ANY_EXTEND ||
54517          InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
54518          InOpcode == ISD::ZERO_EXTEND ||
54519          InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
54520          InOpcode == ISD::SIGN_EXTEND ||
54521          InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
54522         (SizeInBits == 128 || SizeInBits == 256) &&
54523         InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
54524       SDLoc DL(N);
54525       SDValue Ext = InVec.getOperand(0);
54526       if (Ext.getValueSizeInBits() > SizeInBits)
54527         Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
54528       unsigned ExtOp = getOpcode_EXTEND_VECTOR_INREG(InOpcode);
54529       return DAG.getNode(ExtOp, DL, VT, Ext);
54530     }
54531     if (IdxVal == 0 && InOpcode == ISD::VSELECT &&
54532         InVec.getOperand(0).getValueType().is256BitVector() &&
54533         InVec.getOperand(1).getValueType().is256BitVector() &&
54534         InVec.getOperand(2).getValueType().is256BitVector()) {
54535       SDLoc DL(N);
54536       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
54537       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
54538       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
54539       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
54540     }
54541     if (IdxVal == 0 && InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
54542         (VT.is128BitVector() || VT.is256BitVector())) {
54543       SDLoc DL(N);
54544       SDValue InVecSrc = InVec.getOperand(0);
54545       unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
54546       SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
54547       return DAG.getNode(InOpcode, DL, VT, Ext);
54548     }
54549     if (InOpcode == X86ISD::MOVDDUP &&
54550         (VT.is128BitVector() || VT.is256BitVector())) {
54551       SDLoc DL(N);
54552       SDValue Ext0 =
54553           extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
54554       return DAG.getNode(InOpcode, DL, VT, Ext0);
54555     }
54556   }
54557 
54558   // Always split vXi64 logical shifts where we're extracting the upper 32-bits
54559   // as this is very likely to fold into a shuffle/truncation.
54560   if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
54561       InVecVT.getScalarSizeInBits() == 64 &&
54562       InVec.getConstantOperandAPInt(1) == 32) {
54563     SDLoc DL(N);
54564     SDValue Ext =
54565         extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
54566     return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
54567   }
54568 
54569   return SDValue();
54570 }
54571 
54572 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
54573   EVT VT = N->getValueType(0);
54574   SDValue Src = N->getOperand(0);
54575   SDLoc DL(N);
54576 
54577   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
54578   // This occurs frequently in our masked scalar intrinsic code and our
54579   // floating point select lowering with AVX512.
54580   // TODO: SimplifyDemandedBits instead?
54581   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
54582     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
54583       if (C->getAPIntValue().isOne())
54584         return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
54585                            Src.getOperand(0));
54586 
54587   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
54588   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
54589       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
54590       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
54591     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
54592       if (C->isZero())
54593         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
54594                            Src.getOperand(1));
54595 
54596   // Reduce v2i64 to v4i32 if we don't need the upper bits.
54597   // TODO: Move to DAGCombine/SimplifyDemandedBits?
54598   if (VT == MVT::v2i64 || VT == MVT::v2f64) {
54599     auto IsAnyExt64 = [](SDValue Op) {
54600       if (Op.getValueType() != MVT::i64 || !Op.hasOneUse())
54601         return SDValue();
54602       if (Op.getOpcode() == ISD::ANY_EXTEND &&
54603           Op.getOperand(0).getScalarValueSizeInBits() <= 32)
54604         return Op.getOperand(0);
54605       if (auto *Ld = dyn_cast<LoadSDNode>(Op))
54606         if (Ld->getExtensionType() == ISD::EXTLOAD &&
54607             Ld->getMemoryVT().getScalarSizeInBits() <= 32)
54608           return Op;
54609       return SDValue();
54610     };
54611     if (SDValue ExtSrc = IsAnyExt64(peekThroughOneUseBitcasts(Src)))
54612       return DAG.getBitcast(
54613           VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
54614                           DAG.getAnyExtOrTrunc(ExtSrc, DL, MVT::i32)));
54615   }
54616 
54617   // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
54618   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
54619       Src.getOperand(0).getValueType() == MVT::x86mmx)
54620     return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
54621 
54622   // See if we're broadcasting the scalar value, in which case just reuse that.
54623   // Ensure the same SDValue from the SDNode use is being used.
54624   if (VT.getScalarType() == Src.getValueType())
54625     for (SDNode *User : Src->uses())
54626       if (User->getOpcode() == X86ISD::VBROADCAST &&
54627           Src == User->getOperand(0)) {
54628         unsigned SizeInBits = VT.getFixedSizeInBits();
54629         unsigned BroadcastSizeInBits =
54630             User->getValueSizeInBits(0).getFixedSize();
54631         if (BroadcastSizeInBits == SizeInBits)
54632           return SDValue(User, 0);
54633         if (BroadcastSizeInBits > SizeInBits)
54634           return extractSubVector(SDValue(User, 0), 0, DAG, DL, SizeInBits);
54635         // TODO: Handle BroadcastSizeInBits < SizeInBits when we have test
54636         // coverage.
54637       }
54638 
54639   return SDValue();
54640 }
54641 
54642 // Simplify PMULDQ and PMULUDQ operations.
54643 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
54644                              TargetLowering::DAGCombinerInfo &DCI,
54645                              const X86Subtarget &Subtarget) {
54646   SDValue LHS = N->getOperand(0);
54647   SDValue RHS = N->getOperand(1);
54648 
54649   // Canonicalize constant to RHS.
54650   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
54651       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
54652     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
54653 
54654   // Multiply by zero.
54655   // Don't return RHS as it may contain UNDEFs.
54656   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
54657     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
54658 
54659   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
54660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54661   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(64), DCI))
54662     return SDValue(N, 0);
54663 
54664   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
54665   // convert it to any_extend_invec, due to the LegalOperations check, do the
54666   // conversion directly to a vector shuffle manually. This exposes combine
54667   // opportunities missed by combineEXTEND_VECTOR_INREG not calling
54668   // combineX86ShufflesRecursively on SSE4.1 targets.
54669   // FIXME: This is basically a hack around several other issues related to
54670   // ANY_EXTEND_VECTOR_INREG.
54671   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
54672       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
54673        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
54674       LHS.getOperand(0).getValueType() == MVT::v4i32) {
54675     SDLoc dl(N);
54676     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
54677                                LHS.getOperand(0), { 0, -1, 1, -1 });
54678     LHS = DAG.getBitcast(MVT::v2i64, LHS);
54679     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
54680   }
54681   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
54682       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
54683        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
54684       RHS.getOperand(0).getValueType() == MVT::v4i32) {
54685     SDLoc dl(N);
54686     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
54687                                RHS.getOperand(0), { 0, -1, 1, -1 });
54688     RHS = DAG.getBitcast(MVT::v2i64, RHS);
54689     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
54690   }
54691 
54692   return SDValue();
54693 }
54694 
54695 // Simplify VPMADDUBSW/VPMADDWD operations.
54696 static SDValue combineVPMADD(SDNode *N, SelectionDAG &DAG,
54697                              TargetLowering::DAGCombinerInfo &DCI) {
54698   EVT VT = N->getValueType(0);
54699   SDValue LHS = N->getOperand(0);
54700   SDValue RHS = N->getOperand(1);
54701 
54702   // Multiply by zero.
54703   // Don't return LHS/RHS as it may contain UNDEFs.
54704   if (ISD::isBuildVectorAllZeros(LHS.getNode()) ||
54705       ISD::isBuildVectorAllZeros(RHS.getNode()))
54706     return DAG.getConstant(0, SDLoc(N), VT);
54707 
54708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54709   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
54710   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
54711     return SDValue(N, 0);
54712 
54713   return SDValue();
54714 }
54715 
54716 static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
54717                                           TargetLowering::DAGCombinerInfo &DCI,
54718                                           const X86Subtarget &Subtarget) {
54719   EVT VT = N->getValueType(0);
54720   SDValue In = N->getOperand(0);
54721   unsigned Opcode = N->getOpcode();
54722   unsigned InOpcode = In.getOpcode();
54723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54724   SDLoc DL(N);
54725 
54726   // Try to merge vector loads and extend_inreg to an extload.
54727   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
54728       In.hasOneUse()) {
54729     auto *Ld = cast<LoadSDNode>(In);
54730     if (Ld->isSimple()) {
54731       MVT SVT = In.getSimpleValueType().getVectorElementType();
54732       ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
54733                                  ? ISD::SEXTLOAD
54734                                  : ISD::ZEXTLOAD;
54735       EVT MemVT = VT.changeVectorElementType(SVT);
54736       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
54737         SDValue Load = DAG.getExtLoad(
54738             Ext, DL, VT, Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
54739             MemVT, Ld->getOriginalAlign(), Ld->getMemOperand()->getFlags());
54740         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
54741         return Load;
54742       }
54743     }
54744   }
54745 
54746   // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
54747   if (Opcode == InOpcode)
54748     return DAG.getNode(Opcode, DL, VT, In.getOperand(0));
54749 
54750   // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
54751   // -> EXTEND_VECTOR_INREG(X).
54752   // TODO: Handle non-zero subvector indices.
54753   if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
54754       In.getOperand(0).getOpcode() == getOpcode_EXTEND(Opcode) &&
54755       In.getOperand(0).getOperand(0).getValueSizeInBits() ==
54756           In.getValueSizeInBits())
54757     return DAG.getNode(Opcode, DL, VT, In.getOperand(0).getOperand(0));
54758 
54759   // Fold EXTEND_VECTOR_INREG(BUILD_VECTOR(X,Y,?,?)) -> BUILD_VECTOR(X,0,Y,0).
54760   // TODO: Move to DAGCombine?
54761   if (!DCI.isBeforeLegalizeOps() && Opcode == ISD::ZERO_EXTEND_VECTOR_INREG &&
54762       In.getOpcode() == ISD::BUILD_VECTOR && In.hasOneUse() &&
54763       In.getValueSizeInBits() == VT.getSizeInBits()) {
54764     unsigned NumElts = VT.getVectorNumElements();
54765     unsigned Scale = VT.getScalarSizeInBits() / In.getScalarValueSizeInBits();
54766     EVT EltVT = In.getOperand(0).getValueType();
54767     SmallVector<SDValue> Elts(Scale * NumElts, DAG.getConstant(0, DL, EltVT));
54768     for (unsigned I = 0; I != NumElts; ++I)
54769       Elts[I * Scale] = In.getOperand(I);
54770     return DAG.getBitcast(VT, DAG.getBuildVector(In.getValueType(), DL, Elts));
54771   }
54772 
54773   // Attempt to combine as a shuffle on SSE41+ targets.
54774   if ((Opcode == ISD::ANY_EXTEND_VECTOR_INREG ||
54775        Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) &&
54776       Subtarget.hasSSE41()) {
54777     SDValue Op(N, 0);
54778     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
54779       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
54780         return Res;
54781   }
54782 
54783   return SDValue();
54784 }
54785 
54786 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
54787                              TargetLowering::DAGCombinerInfo &DCI) {
54788   EVT VT = N->getValueType(0);
54789 
54790   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
54791     return DAG.getConstant(0, SDLoc(N), VT);
54792 
54793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54794   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
54795   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
54796     return SDValue(N, 0);
54797 
54798   return SDValue();
54799 }
54800 
54801 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
54802 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
54803 // extra instructions between the conversion due to going to scalar and back.
54804 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
54805                                  const X86Subtarget &Subtarget) {
54806   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
54807     return SDValue();
54808 
54809   if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
54810     return SDValue();
54811 
54812   if (N->getValueType(0) != MVT::f32 ||
54813       N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
54814     return SDValue();
54815 
54816   SDLoc dl(N);
54817   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
54818                             N->getOperand(0).getOperand(0));
54819   Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
54820                     DAG.getTargetConstant(4, dl, MVT::i32));
54821   Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
54822   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
54823                      DAG.getIntPtrConstant(0, dl));
54824 }
54825 
54826 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
54827                                 const X86Subtarget &Subtarget) {
54828   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
54829     return SDValue();
54830 
54831   if (Subtarget.hasFP16())
54832     return SDValue();
54833 
54834   bool IsStrict = N->isStrictFPOpcode();
54835   EVT VT = N->getValueType(0);
54836   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
54837   EVT SrcVT = Src.getValueType();
54838 
54839   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
54840     return SDValue();
54841 
54842   if (VT.getVectorElementType() != MVT::f32 &&
54843       VT.getVectorElementType() != MVT::f64)
54844     return SDValue();
54845 
54846   unsigned NumElts = VT.getVectorNumElements();
54847   if (NumElts == 1 || !isPowerOf2_32(NumElts))
54848     return SDValue();
54849 
54850   SDLoc dl(N);
54851 
54852   // Convert the input to vXi16.
54853   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
54854   Src = DAG.getBitcast(IntVT, Src);
54855 
54856   // Widen to at least 8 input elements.
54857   if (NumElts < 8) {
54858     unsigned NumConcats = 8 / NumElts;
54859     SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
54860                                 : DAG.getConstant(0, dl, IntVT);
54861     SmallVector<SDValue, 4> Ops(NumConcats, Fill);
54862     Ops[0] = Src;
54863     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
54864   }
54865 
54866   // Destination is vXf32 with at least 4 elements.
54867   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
54868                                std::max(4U, NumElts));
54869   SDValue Cvt, Chain;
54870   if (IsStrict) {
54871     Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
54872                       {N->getOperand(0), Src});
54873     Chain = Cvt.getValue(1);
54874   } else {
54875     Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
54876   }
54877 
54878   if (NumElts < 4) {
54879     assert(NumElts == 2 && "Unexpected size");
54880     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
54881                       DAG.getIntPtrConstant(0, dl));
54882   }
54883 
54884   if (IsStrict) {
54885     // Extend to the original VT if necessary.
54886     if (Cvt.getValueType() != VT) {
54887       Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
54888                         {Chain, Cvt});
54889       Chain = Cvt.getValue(1);
54890     }
54891     return DAG.getMergeValues({Cvt, Chain}, dl);
54892   }
54893 
54894   // Extend to the original VT if necessary.
54895   return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
54896 }
54897 
54898 // Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
54899 // from. Limit this to cases where the loads have the same input chain and the
54900 // output chains are unused. This avoids any memory ordering issues.
54901 static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
54902                                      TargetLowering::DAGCombinerInfo &DCI) {
54903   assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||
54904           N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
54905          "Unknown broadcast load type");
54906 
54907   // Only do this if the chain result is unused.
54908   if (N->hasAnyUseOfValue(1))
54909     return SDValue();
54910 
54911   auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
54912 
54913   SDValue Ptr = MemIntrin->getBasePtr();
54914   SDValue Chain = MemIntrin->getChain();
54915   EVT VT = N->getSimpleValueType(0);
54916   EVT MemVT = MemIntrin->getMemoryVT();
54917 
54918   // Look at other users of our base pointer and try to find a wider broadcast.
54919   // The input chain and the size of the memory VT must match.
54920   for (SDNode *User : Ptr->uses())
54921     if (User != N && User->getOpcode() == N->getOpcode() &&
54922         cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
54923         cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
54924         cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
54925             MemVT.getSizeInBits() &&
54926         !User->hasAnyUseOfValue(1) &&
54927         User->getValueSizeInBits(0).getFixedSize() > VT.getFixedSizeInBits()) {
54928       SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
54929                                          VT.getSizeInBits());
54930       Extract = DAG.getBitcast(VT, Extract);
54931       return DCI.CombineTo(N, Extract, SDValue(User, 1));
54932     }
54933 
54934   return SDValue();
54935 }
54936 
54937 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
54938                                const X86Subtarget &Subtarget) {
54939   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
54940     return SDValue();
54941 
54942   if (Subtarget.hasFP16())
54943     return SDValue();
54944 
54945   bool IsStrict = N->isStrictFPOpcode();
54946   EVT VT = N->getValueType(0);
54947   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
54948   EVT SrcVT = Src.getValueType();
54949 
54950   if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
54951       SrcVT.getVectorElementType() != MVT::f32)
54952     return SDValue();
54953 
54954   unsigned NumElts = VT.getVectorNumElements();
54955   if (NumElts == 1 || !isPowerOf2_32(NumElts))
54956     return SDValue();
54957 
54958   SDLoc dl(N);
54959 
54960   // Widen to at least 4 input elements.
54961   if (NumElts < 4)
54962     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
54963                       DAG.getConstantFP(0.0, dl, SrcVT));
54964 
54965   // Destination is v8i16 with at least 8 elements.
54966   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
54967                                std::max(8U, NumElts));
54968   SDValue Cvt, Chain;
54969   SDValue Rnd = DAG.getTargetConstant(4, dl, MVT::i32);
54970   if (IsStrict) {
54971     Cvt = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {CvtVT, MVT::Other},
54972                       {N->getOperand(0), Src, Rnd});
54973     Chain = Cvt.getValue(1);
54974   } else {
54975     Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src, Rnd);
54976   }
54977 
54978   // Extract down to real number of elements.
54979   if (NumElts < 8) {
54980     EVT IntVT = VT.changeVectorElementTypeToInteger();
54981     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
54982                       DAG.getIntPtrConstant(0, dl));
54983   }
54984 
54985   Cvt = DAG.getBitcast(VT, Cvt);
54986 
54987   if (IsStrict)
54988     return DAG.getMergeValues({Cvt, Chain}, dl);
54989 
54990   return Cvt;
54991 }
54992 
54993 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
54994   SDValue Src = N->getOperand(0);
54995 
54996   // Turn MOVDQ2Q+simple_load into an mmx load.
54997   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
54998     LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
54999 
55000     if (LN->isSimple()) {
55001       SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
55002                                   LN->getBasePtr(),
55003                                   LN->getPointerInfo(),
55004                                   LN->getOriginalAlign(),
55005                                   LN->getMemOperand()->getFlags());
55006       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
55007       return NewLd;
55008     }
55009   }
55010 
55011   return SDValue();
55012 }
55013 
55014 static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
55015                            TargetLowering::DAGCombinerInfo &DCI) {
55016   unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
55017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55018   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBits), DCI))
55019     return SDValue(N, 0);
55020 
55021   return SDValue();
55022 }
55023 
55024 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
55025                                              DAGCombinerInfo &DCI) const {
55026   SelectionDAG &DAG = DCI.DAG;
55027   switch (N->getOpcode()) {
55028   default: break;
55029   case ISD::SCALAR_TO_VECTOR:
55030     return combineScalarToVector(N, DAG);
55031   case ISD::EXTRACT_VECTOR_ELT:
55032   case X86ISD::PEXTRW:
55033   case X86ISD::PEXTRB:
55034     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
55035   case ISD::CONCAT_VECTORS:
55036     return combineCONCAT_VECTORS(N, DAG, DCI, Subtarget);
55037   case ISD::INSERT_SUBVECTOR:
55038     return combineINSERT_SUBVECTOR(N, DAG, DCI, Subtarget);
55039   case ISD::EXTRACT_SUBVECTOR:
55040     return combineEXTRACT_SUBVECTOR(N, DAG, DCI, Subtarget);
55041   case ISD::VSELECT:
55042   case ISD::SELECT:
55043   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
55044   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
55045   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
55046   case X86ISD::CMP:         return combineCMP(N, DAG);
55047   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
55048   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
55049   case X86ISD::ADD:
55050   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
55051   case X86ISD::SBB:         return combineSBB(N, DAG);
55052   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
55053   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
55054   case ISD::SHL:            return combineShiftLeft(N, DAG);
55055   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG, Subtarget);
55056   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI, Subtarget);
55057   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
55058   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
55059   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
55060   case X86ISD::BEXTR:
55061   case X86ISD::BEXTRI:      return combineBEXTR(N, DAG, DCI, Subtarget);
55062   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
55063   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
55064   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
55065   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
55066   case X86ISD::VEXTRACT_STORE:
55067     return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
55068   case ISD::SINT_TO_FP:
55069   case ISD::STRICT_SINT_TO_FP:
55070     return combineSIntToFP(N, DAG, DCI, Subtarget);
55071   case ISD::UINT_TO_FP:
55072   case ISD::STRICT_UINT_TO_FP:
55073     return combineUIntToFP(N, DAG, Subtarget);
55074   case ISD::FADD:
55075   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
55076   case X86ISD::VFCMULC:
55077   case X86ISD::VFMULC:      return combineFMulcFCMulc(N, DAG, Subtarget);
55078   case ISD::FNEG:           return combineFneg(N, DAG, DCI, Subtarget);
55079   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
55080   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG, DCI);
55081   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
55082   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
55083   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
55084   case X86ISD::FXOR:
55085   case X86ISD::FOR:         return combineFOr(N, DAG, DCI, Subtarget);
55086   case X86ISD::FMIN:
55087   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
55088   case ISD::FMINNUM:
55089   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
55090   case X86ISD::CVTSI2P:
55091   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
55092   case X86ISD::CVTP2SI:
55093   case X86ISD::CVTP2UI:
55094   case X86ISD::STRICT_CVTTP2SI:
55095   case X86ISD::CVTTP2SI:
55096   case X86ISD::STRICT_CVTTP2UI:
55097   case X86ISD::CVTTP2UI:
55098                             return combineCVTP2I_CVTTP2I(N, DAG, DCI);
55099   case X86ISD::STRICT_CVTPH2PS:
55100   case X86ISD::CVTPH2PS:    return combineCVTPH2PS(N, DAG, DCI);
55101   case X86ISD::BT:          return combineBT(N, DAG, DCI);
55102   case ISD::ANY_EXTEND:
55103   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
55104   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
55105   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
55106   case ISD::ANY_EXTEND_VECTOR_INREG:
55107   case ISD::SIGN_EXTEND_VECTOR_INREG:
55108   case ISD::ZERO_EXTEND_VECTOR_INREG:
55109     return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
55110   case ISD::SETCC:          return combineSetCC(N, DAG, DCI, Subtarget);
55111   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
55112   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
55113   case X86ISD::PACKSS:
55114   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
55115   case X86ISD::HADD:
55116   case X86ISD::HSUB:
55117   case X86ISD::FHADD:
55118   case X86ISD::FHSUB:       return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
55119   case X86ISD::VSHL:
55120   case X86ISD::VSRA:
55121   case X86ISD::VSRL:
55122     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
55123   case X86ISD::VSHLI:
55124   case X86ISD::VSRAI:
55125   case X86ISD::VSRLI:
55126     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
55127   case ISD::INSERT_VECTOR_ELT:
55128   case X86ISD::PINSRB:
55129   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
55130   case X86ISD::SHUFP:       // Handle all target specific shuffles
55131   case X86ISD::INSERTPS:
55132   case X86ISD::EXTRQI:
55133   case X86ISD::INSERTQI:
55134   case X86ISD::VALIGN:
55135   case X86ISD::PALIGNR:
55136   case X86ISD::VSHLDQ:
55137   case X86ISD::VSRLDQ:
55138   case X86ISD::BLENDI:
55139   case X86ISD::UNPCKH:
55140   case X86ISD::UNPCKL:
55141   case X86ISD::MOVHLPS:
55142   case X86ISD::MOVLHPS:
55143   case X86ISD::PSHUFB:
55144   case X86ISD::PSHUFD:
55145   case X86ISD::PSHUFHW:
55146   case X86ISD::PSHUFLW:
55147   case X86ISD::MOVSHDUP:
55148   case X86ISD::MOVSLDUP:
55149   case X86ISD::MOVDDUP:
55150   case X86ISD::MOVSS:
55151   case X86ISD::MOVSD:
55152   case X86ISD::MOVSH:
55153   case X86ISD::VBROADCAST:
55154   case X86ISD::VPPERM:
55155   case X86ISD::VPERMI:
55156   case X86ISD::VPERMV:
55157   case X86ISD::VPERMV3:
55158   case X86ISD::VPERMIL2:
55159   case X86ISD::VPERMILPI:
55160   case X86ISD::VPERMILPV:
55161   case X86ISD::VPERM2X128:
55162   case X86ISD::SHUF128:
55163   case X86ISD::VZEXT_MOVL:
55164   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
55165   case X86ISD::FMADD_RND:
55166   case X86ISD::FMSUB:
55167   case X86ISD::STRICT_FMSUB:
55168   case X86ISD::FMSUB_RND:
55169   case X86ISD::FNMADD:
55170   case X86ISD::STRICT_FNMADD:
55171   case X86ISD::FNMADD_RND:
55172   case X86ISD::FNMSUB:
55173   case X86ISD::STRICT_FNMSUB:
55174   case X86ISD::FNMSUB_RND:
55175   case ISD::FMA:
55176   case ISD::STRICT_FMA:     return combineFMA(N, DAG, DCI, Subtarget);
55177   case X86ISD::FMADDSUB_RND:
55178   case X86ISD::FMSUBADD_RND:
55179   case X86ISD::FMADDSUB:
55180   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
55181   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
55182   case X86ISD::MGATHER:
55183   case X86ISD::MSCATTER:
55184     return combineX86GatherScatter(N, DAG, DCI, Subtarget);
55185   case ISD::MGATHER:
55186   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
55187   case X86ISD::PCMPEQ:
55188   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
55189   case X86ISD::PMULDQ:
55190   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
55191   case X86ISD::VPMADDUBSW:
55192   case X86ISD::VPMADDWD:    return combineVPMADD(N, DAG, DCI);
55193   case X86ISD::KSHIFTL:
55194   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
55195   case ISD::FP16_TO_FP:     return combineFP16_TO_FP(N, DAG, Subtarget);
55196   case ISD::STRICT_FP_EXTEND:
55197   case ISD::FP_EXTEND:      return combineFP_EXTEND(N, DAG, Subtarget);
55198   case ISD::STRICT_FP_ROUND:
55199   case ISD::FP_ROUND:       return combineFP_ROUND(N, DAG, Subtarget);
55200   case X86ISD::VBROADCAST_LOAD:
55201   case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
55202   case X86ISD::MOVDQ2Q:     return combineMOVDQ2Q(N, DAG);
55203   case X86ISD::PDEP:        return combinePDEP(N, DAG, DCI);
55204   }
55205 
55206   return SDValue();
55207 }
55208 
55209 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
55210   if (!isTypeLegal(VT))
55211     return false;
55212 
55213   // There are no vXi8 shifts.
55214   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
55215     return false;
55216 
55217   // TODO: Almost no 8-bit ops are desirable because they have no actual
55218   //       size/speed advantages vs. 32-bit ops, but they do have a major
55219   //       potential disadvantage by causing partial register stalls.
55220   //
55221   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
55222   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
55223   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
55224   // check for a constant operand to the multiply.
55225   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
55226     return false;
55227 
55228   // i16 instruction encodings are longer and some i16 instructions are slow,
55229   // so those are not desirable.
55230   if (VT == MVT::i16) {
55231     switch (Opc) {
55232     default:
55233       break;
55234     case ISD::LOAD:
55235     case ISD::SIGN_EXTEND:
55236     case ISD::ZERO_EXTEND:
55237     case ISD::ANY_EXTEND:
55238     case ISD::SHL:
55239     case ISD::SRA:
55240     case ISD::SRL:
55241     case ISD::SUB:
55242     case ISD::ADD:
55243     case ISD::MUL:
55244     case ISD::AND:
55245     case ISD::OR:
55246     case ISD::XOR:
55247       return false;
55248     }
55249   }
55250 
55251   // Any legal type not explicitly accounted for above here is desirable.
55252   return true;
55253 }
55254 
55255 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
55256                                                   SDValue Value, SDValue Addr,
55257                                                   SelectionDAG &DAG) const {
55258   const Module *M = DAG.getMachineFunction().getMMI().getModule();
55259   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
55260   if (IsCFProtectionSupported) {
55261     // In case control-flow branch protection is enabled, we need to add
55262     // notrack prefix to the indirect branch.
55263     // In order to do that we create NT_BRIND SDNode.
55264     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
55265     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
55266   }
55267 
55268   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
55269 }
55270 
55271 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
55272   EVT VT = Op.getValueType();
55273   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
55274                              isa<ConstantSDNode>(Op.getOperand(1));
55275 
55276   // i16 is legal, but undesirable since i16 instruction encodings are longer
55277   // and some i16 instructions are slow.
55278   // 8-bit multiply-by-constant can usually be expanded to something cheaper
55279   // using LEA and/or other ALU ops.
55280   if (VT != MVT::i16 && !Is8BitMulByConstant)
55281     return false;
55282 
55283   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
55284     if (!Op.hasOneUse())
55285       return false;
55286     SDNode *User = *Op->use_begin();
55287     if (!ISD::isNormalStore(User))
55288       return false;
55289     auto *Ld = cast<LoadSDNode>(Load);
55290     auto *St = cast<StoreSDNode>(User);
55291     return Ld->getBasePtr() == St->getBasePtr();
55292   };
55293 
55294   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
55295     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
55296       return false;
55297     if (!Op.hasOneUse())
55298       return false;
55299     SDNode *User = *Op->use_begin();
55300     if (User->getOpcode() != ISD::ATOMIC_STORE)
55301       return false;
55302     auto *Ld = cast<AtomicSDNode>(Load);
55303     auto *St = cast<AtomicSDNode>(User);
55304     return Ld->getBasePtr() == St->getBasePtr();
55305   };
55306 
55307   bool Commute = false;
55308   switch (Op.getOpcode()) {
55309   default: return false;
55310   case ISD::SIGN_EXTEND:
55311   case ISD::ZERO_EXTEND:
55312   case ISD::ANY_EXTEND:
55313     break;
55314   case ISD::SHL:
55315   case ISD::SRA:
55316   case ISD::SRL: {
55317     SDValue N0 = Op.getOperand(0);
55318     // Look out for (store (shl (load), x)).
55319     if (X86::mayFoldLoad(N0, Subtarget) && IsFoldableRMW(N0, Op))
55320       return false;
55321     break;
55322   }
55323   case ISD::ADD:
55324   case ISD::MUL:
55325   case ISD::AND:
55326   case ISD::OR:
55327   case ISD::XOR:
55328     Commute = true;
55329     LLVM_FALLTHROUGH;
55330   case ISD::SUB: {
55331     SDValue N0 = Op.getOperand(0);
55332     SDValue N1 = Op.getOperand(1);
55333     // Avoid disabling potential load folding opportunities.
55334     if (X86::mayFoldLoad(N1, Subtarget) &&
55335         (!Commute || !isa<ConstantSDNode>(N0) ||
55336          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
55337       return false;
55338     if (X86::mayFoldLoad(N0, Subtarget) &&
55339         ((Commute && !isa<ConstantSDNode>(N1)) ||
55340          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
55341       return false;
55342     if (IsFoldableAtomicRMW(N0, Op) ||
55343         (Commute && IsFoldableAtomicRMW(N1, Op)))
55344       return false;
55345   }
55346   }
55347 
55348   PVT = MVT::i32;
55349   return true;
55350 }
55351 
55352 //===----------------------------------------------------------------------===//
55353 //                           X86 Inline Assembly Support
55354 //===----------------------------------------------------------------------===//
55355 
55356 // Helper to match a string separated by whitespace.
55357 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
55358   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
55359 
55360   for (StringRef Piece : Pieces) {
55361     if (!S.startswith(Piece)) // Check if the piece matches.
55362       return false;
55363 
55364     S = S.substr(Piece.size());
55365     StringRef::size_type Pos = S.find_first_not_of(" \t");
55366     if (Pos == 0) // We matched a prefix.
55367       return false;
55368 
55369     S = S.substr(Pos);
55370   }
55371 
55372   return S.empty();
55373 }
55374 
55375 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
55376 
55377   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
55378     if (llvm::is_contained(AsmPieces, "~{cc}") &&
55379         llvm::is_contained(AsmPieces, "~{flags}") &&
55380         llvm::is_contained(AsmPieces, "~{fpsr}")) {
55381 
55382       if (AsmPieces.size() == 3)
55383         return true;
55384       else if (llvm::is_contained(AsmPieces, "~{dirflag}"))
55385         return true;
55386     }
55387   }
55388   return false;
55389 }
55390 
55391 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
55392   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
55393 
55394   const std::string &AsmStr = IA->getAsmString();
55395 
55396   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
55397   if (!Ty || Ty->getBitWidth() % 16 != 0)
55398     return false;
55399 
55400   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
55401   SmallVector<StringRef, 4> AsmPieces;
55402   SplitString(AsmStr, AsmPieces, ";\n");
55403 
55404   switch (AsmPieces.size()) {
55405   default: return false;
55406   case 1:
55407     // FIXME: this should verify that we are targeting a 486 or better.  If not,
55408     // we will turn this bswap into something that will be lowered to logical
55409     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
55410     // lower so don't worry about this.
55411     // bswap $0
55412     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
55413         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
55414         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
55415         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
55416         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
55417         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
55418       // No need to check constraints, nothing other than the equivalent of
55419       // "=r,0" would be valid here.
55420       return IntrinsicLowering::LowerToByteSwap(CI);
55421     }
55422 
55423     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
55424     if (CI->getType()->isIntegerTy(16) &&
55425         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
55426         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
55427          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
55428       AsmPieces.clear();
55429       StringRef ConstraintsStr = IA->getConstraintString();
55430       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
55431       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
55432       if (clobbersFlagRegisters(AsmPieces))
55433         return IntrinsicLowering::LowerToByteSwap(CI);
55434     }
55435     break;
55436   case 3:
55437     if (CI->getType()->isIntegerTy(32) &&
55438         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
55439         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
55440         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
55441         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
55442       AsmPieces.clear();
55443       StringRef ConstraintsStr = IA->getConstraintString();
55444       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
55445       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
55446       if (clobbersFlagRegisters(AsmPieces))
55447         return IntrinsicLowering::LowerToByteSwap(CI);
55448     }
55449 
55450     if (CI->getType()->isIntegerTy(64)) {
55451       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
55452       if (Constraints.size() >= 2 &&
55453           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
55454           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
55455         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
55456         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
55457             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
55458             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
55459           return IntrinsicLowering::LowerToByteSwap(CI);
55460       }
55461     }
55462     break;
55463   }
55464   return false;
55465 }
55466 
55467 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
55468   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
55469                            .Case("{@cca}", X86::COND_A)
55470                            .Case("{@ccae}", X86::COND_AE)
55471                            .Case("{@ccb}", X86::COND_B)
55472                            .Case("{@ccbe}", X86::COND_BE)
55473                            .Case("{@ccc}", X86::COND_B)
55474                            .Case("{@cce}", X86::COND_E)
55475                            .Case("{@ccz}", X86::COND_E)
55476                            .Case("{@ccg}", X86::COND_G)
55477                            .Case("{@ccge}", X86::COND_GE)
55478                            .Case("{@ccl}", X86::COND_L)
55479                            .Case("{@ccle}", X86::COND_LE)
55480                            .Case("{@ccna}", X86::COND_BE)
55481                            .Case("{@ccnae}", X86::COND_B)
55482                            .Case("{@ccnb}", X86::COND_AE)
55483                            .Case("{@ccnbe}", X86::COND_A)
55484                            .Case("{@ccnc}", X86::COND_AE)
55485                            .Case("{@ccne}", X86::COND_NE)
55486                            .Case("{@ccnz}", X86::COND_NE)
55487                            .Case("{@ccng}", X86::COND_LE)
55488                            .Case("{@ccnge}", X86::COND_L)
55489                            .Case("{@ccnl}", X86::COND_GE)
55490                            .Case("{@ccnle}", X86::COND_G)
55491                            .Case("{@ccno}", X86::COND_NO)
55492                            .Case("{@ccnp}", X86::COND_NP)
55493                            .Case("{@ccns}", X86::COND_NS)
55494                            .Case("{@cco}", X86::COND_O)
55495                            .Case("{@ccp}", X86::COND_P)
55496                            .Case("{@ccs}", X86::COND_S)
55497                            .Default(X86::COND_INVALID);
55498   return Cond;
55499 }
55500 
55501 /// Given a constraint letter, return the type of constraint for this target.
55502 X86TargetLowering::ConstraintType
55503 X86TargetLowering::getConstraintType(StringRef Constraint) const {
55504   if (Constraint.size() == 1) {
55505     switch (Constraint[0]) {
55506     case 'R':
55507     case 'q':
55508     case 'Q':
55509     case 'f':
55510     case 't':
55511     case 'u':
55512     case 'y':
55513     case 'x':
55514     case 'v':
55515     case 'l':
55516     case 'k': // AVX512 masking registers.
55517       return C_RegisterClass;
55518     case 'a':
55519     case 'b':
55520     case 'c':
55521     case 'd':
55522     case 'S':
55523     case 'D':
55524     case 'A':
55525       return C_Register;
55526     case 'I':
55527     case 'J':
55528     case 'K':
55529     case 'N':
55530     case 'G':
55531     case 'L':
55532     case 'M':
55533       return C_Immediate;
55534     case 'C':
55535     case 'e':
55536     case 'Z':
55537       return C_Other;
55538     default:
55539       break;
55540     }
55541   }
55542   else if (Constraint.size() == 2) {
55543     switch (Constraint[0]) {
55544     default:
55545       break;
55546     case 'Y':
55547       switch (Constraint[1]) {
55548       default:
55549         break;
55550       case 'z':
55551         return C_Register;
55552       case 'i':
55553       case 'm':
55554       case 'k':
55555       case 't':
55556       case '2':
55557         return C_RegisterClass;
55558       }
55559     }
55560   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
55561     return C_Other;
55562   return TargetLowering::getConstraintType(Constraint);
55563 }
55564 
55565 /// Examine constraint type and operand type and determine a weight value.
55566 /// This object must already have been set up with the operand type
55567 /// and the current alternative constraint selected.
55568 TargetLowering::ConstraintWeight
55569   X86TargetLowering::getSingleConstraintMatchWeight(
55570     AsmOperandInfo &info, const char *constraint) const {
55571   ConstraintWeight weight = CW_Invalid;
55572   Value *CallOperandVal = info.CallOperandVal;
55573     // If we don't have a value, we can't do a match,
55574     // but allow it at the lowest weight.
55575   if (!CallOperandVal)
55576     return CW_Default;
55577   Type *type = CallOperandVal->getType();
55578   // Look at the constraint type.
55579   switch (*constraint) {
55580   default:
55581     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
55582     LLVM_FALLTHROUGH;
55583   case 'R':
55584   case 'q':
55585   case 'Q':
55586   case 'a':
55587   case 'b':
55588   case 'c':
55589   case 'd':
55590   case 'S':
55591   case 'D':
55592   case 'A':
55593     if (CallOperandVal->getType()->isIntegerTy())
55594       weight = CW_SpecificReg;
55595     break;
55596   case 'f':
55597   case 't':
55598   case 'u':
55599     if (type->isFloatingPointTy())
55600       weight = CW_SpecificReg;
55601     break;
55602   case 'y':
55603     if (type->isX86_MMXTy() && Subtarget.hasMMX())
55604       weight = CW_SpecificReg;
55605     break;
55606   case 'Y':
55607     if (StringRef(constraint).size() != 2)
55608       break;
55609     switch (constraint[1]) {
55610       default:
55611         return CW_Invalid;
55612       // XMM0
55613       case 'z':
55614         if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
55615             ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
55616             ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
55617           return CW_SpecificReg;
55618         return CW_Invalid;
55619       // Conditional OpMask regs (AVX512)
55620       case 'k':
55621         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
55622           return CW_Register;
55623         return CW_Invalid;
55624       // Any MMX reg
55625       case 'm':
55626         if (type->isX86_MMXTy() && Subtarget.hasMMX())
55627           return weight;
55628         return CW_Invalid;
55629       // Any SSE reg when ISA >= SSE2, same as 'x'
55630       case 'i':
55631       case 't':
55632       case '2':
55633         if (!Subtarget.hasSSE2())
55634           return CW_Invalid;
55635         break;
55636     }
55637     break;
55638   case 'v':
55639     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
55640       weight = CW_Register;
55641     LLVM_FALLTHROUGH;
55642   case 'x':
55643     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
55644         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
55645       weight = CW_Register;
55646     break;
55647   case 'k':
55648     // Enable conditional vector operations using %k<#> registers.
55649     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
55650       weight = CW_Register;
55651     break;
55652   case 'I':
55653     if (auto *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
55654       if (C->getZExtValue() <= 31)
55655         weight = CW_Constant;
55656     }
55657     break;
55658   case 'J':
55659     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55660       if (C->getZExtValue() <= 63)
55661         weight = CW_Constant;
55662     }
55663     break;
55664   case 'K':
55665     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55666       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
55667         weight = CW_Constant;
55668     }
55669     break;
55670   case 'L':
55671     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55672       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
55673         weight = CW_Constant;
55674     }
55675     break;
55676   case 'M':
55677     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55678       if (C->getZExtValue() <= 3)
55679         weight = CW_Constant;
55680     }
55681     break;
55682   case 'N':
55683     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55684       if (C->getZExtValue() <= 0xff)
55685         weight = CW_Constant;
55686     }
55687     break;
55688   case 'G':
55689   case 'C':
55690     if (isa<ConstantFP>(CallOperandVal)) {
55691       weight = CW_Constant;
55692     }
55693     break;
55694   case 'e':
55695     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55696       if ((C->getSExtValue() >= -0x80000000LL) &&
55697           (C->getSExtValue() <= 0x7fffffffLL))
55698         weight = CW_Constant;
55699     }
55700     break;
55701   case 'Z':
55702     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
55703       if (C->getZExtValue() <= 0xffffffff)
55704         weight = CW_Constant;
55705     }
55706     break;
55707   }
55708   return weight;
55709 }
55710 
55711 /// Try to replace an X constraint, which matches anything, with another that
55712 /// has more specific requirements based on the type of the corresponding
55713 /// operand.
55714 const char *X86TargetLowering::
55715 LowerXConstraint(EVT ConstraintVT) const {
55716   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
55717   // 'f' like normal targets.
55718   if (ConstraintVT.isFloatingPoint()) {
55719     if (Subtarget.hasSSE1())
55720       return "x";
55721   }
55722 
55723   return TargetLowering::LowerXConstraint(ConstraintVT);
55724 }
55725 
55726 // Lower @cc targets via setcc.
55727 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
55728     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
55729     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
55730   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
55731   if (Cond == X86::COND_INVALID)
55732     return SDValue();
55733   // Check that return type is valid.
55734   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
55735       OpInfo.ConstraintVT.getSizeInBits() < 8)
55736     report_fatal_error("Flag output operand is of invalid type");
55737 
55738   // Get EFLAGS register. Only update chain when copyfrom is glued.
55739   if (Flag.getNode()) {
55740     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
55741     Chain = Flag.getValue(1);
55742   } else
55743     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
55744   // Extract CC code.
55745   SDValue CC = getSETCC(Cond, Flag, DL, DAG);
55746   // Extend to 32-bits
55747   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
55748 
55749   return Result;
55750 }
55751 
55752 /// Lower the specified operand into the Ops vector.
55753 /// If it is invalid, don't add anything to Ops.
55754 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
55755                                                      std::string &Constraint,
55756                                                      std::vector<SDValue>&Ops,
55757                                                      SelectionDAG &DAG) const {
55758   SDValue Result;
55759 
55760   // Only support length 1 constraints for now.
55761   if (Constraint.length() > 1) return;
55762 
55763   char ConstraintLetter = Constraint[0];
55764   switch (ConstraintLetter) {
55765   default: break;
55766   case 'I':
55767     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55768       if (C->getZExtValue() <= 31) {
55769         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55770                                        Op.getValueType());
55771         break;
55772       }
55773     }
55774     return;
55775   case 'J':
55776     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55777       if (C->getZExtValue() <= 63) {
55778         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55779                                        Op.getValueType());
55780         break;
55781       }
55782     }
55783     return;
55784   case 'K':
55785     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55786       if (isInt<8>(C->getSExtValue())) {
55787         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55788                                        Op.getValueType());
55789         break;
55790       }
55791     }
55792     return;
55793   case 'L':
55794     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55795       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
55796           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
55797         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
55798                                        Op.getValueType());
55799         break;
55800       }
55801     }
55802     return;
55803   case 'M':
55804     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55805       if (C->getZExtValue() <= 3) {
55806         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55807                                        Op.getValueType());
55808         break;
55809       }
55810     }
55811     return;
55812   case 'N':
55813     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55814       if (C->getZExtValue() <= 255) {
55815         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55816                                        Op.getValueType());
55817         break;
55818       }
55819     }
55820     return;
55821   case 'O':
55822     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55823       if (C->getZExtValue() <= 127) {
55824         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55825                                        Op.getValueType());
55826         break;
55827       }
55828     }
55829     return;
55830   case 'e': {
55831     // 32-bit signed value
55832     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55833       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
55834                                            C->getSExtValue())) {
55835         // Widen to 64 bits here to get it sign extended.
55836         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
55837         break;
55838       }
55839     // FIXME gcc accepts some relocatable values here too, but only in certain
55840     // memory models; it's complicated.
55841     }
55842     return;
55843   }
55844   case 'Z': {
55845     // 32-bit unsigned value
55846     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
55847       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
55848                                            C->getZExtValue())) {
55849         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
55850                                        Op.getValueType());
55851         break;
55852       }
55853     }
55854     // FIXME gcc accepts some relocatable values here too, but only in certain
55855     // memory models; it's complicated.
55856     return;
55857   }
55858   case 'i': {
55859     // Literal immediates are always ok.
55860     if (auto *CST = dyn_cast<ConstantSDNode>(Op)) {
55861       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
55862       BooleanContent BCont = getBooleanContents(MVT::i64);
55863       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
55864                                     : ISD::SIGN_EXTEND;
55865       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
55866                                                   : CST->getSExtValue();
55867       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
55868       break;
55869     }
55870 
55871     // In any sort of PIC mode addresses need to be computed at runtime by
55872     // adding in a register or some sort of table lookup.  These can't
55873     // be used as immediates. BlockAddresses are fine though.
55874     if ((Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC()) &&
55875         !isa<BlockAddressSDNode>(Op))
55876       return;
55877 
55878     // If we are in non-pic codegen mode, we allow the address of a global (with
55879     // an optional displacement) to be used with 'i'.
55880     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
55881       // If we require an extra load to get this address, as in PIC mode, we
55882       // can't accept it.
55883       if (isGlobalStubReference(
55884               Subtarget.classifyGlobalReference(GA->getGlobal())))
55885         return;
55886     break;
55887   }
55888   }
55889 
55890   if (Result.getNode()) {
55891     Ops.push_back(Result);
55892     return;
55893   }
55894   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
55895 }
55896 
55897 /// Check if \p RC is a general purpose register class.
55898 /// I.e., GR* or one of their variant.
55899 static bool isGRClass(const TargetRegisterClass &RC) {
55900   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
55901          RC.hasSuperClassEq(&X86::GR16RegClass) ||
55902          RC.hasSuperClassEq(&X86::GR32RegClass) ||
55903          RC.hasSuperClassEq(&X86::GR64RegClass) ||
55904          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
55905 }
55906 
55907 /// Check if \p RC is a vector register class.
55908 /// I.e., FR* / VR* or one of their variant.
55909 static bool isFRClass(const TargetRegisterClass &RC) {
55910   return RC.hasSuperClassEq(&X86::FR16XRegClass) ||
55911          RC.hasSuperClassEq(&X86::FR32XRegClass) ||
55912          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
55913          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
55914          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
55915          RC.hasSuperClassEq(&X86::VR512RegClass);
55916 }
55917 
55918 /// Check if \p RC is a mask register class.
55919 /// I.e., VK* or one of their variant.
55920 static bool isVKClass(const TargetRegisterClass &RC) {
55921   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
55922          RC.hasSuperClassEq(&X86::VK2RegClass) ||
55923          RC.hasSuperClassEq(&X86::VK4RegClass) ||
55924          RC.hasSuperClassEq(&X86::VK8RegClass) ||
55925          RC.hasSuperClassEq(&X86::VK16RegClass) ||
55926          RC.hasSuperClassEq(&X86::VK32RegClass) ||
55927          RC.hasSuperClassEq(&X86::VK64RegClass);
55928 }
55929 
55930 std::pair<unsigned, const TargetRegisterClass *>
55931 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
55932                                                 StringRef Constraint,
55933                                                 MVT VT) const {
55934   // First, see if this is a constraint that directly corresponds to an LLVM
55935   // register class.
55936   if (Constraint.size() == 1) {
55937     // GCC Constraint Letters
55938     switch (Constraint[0]) {
55939     default: break;
55940     // 'A' means [ER]AX + [ER]DX.
55941     case 'A':
55942       if (Subtarget.is64Bit())
55943         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
55944       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
55945              "Expecting 64, 32 or 16 bit subtarget");
55946       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
55947 
55948       // TODO: Slight differences here in allocation order and leaving
55949       // RIP in the class. Do they matter any more here than they do
55950       // in the normal allocation?
55951     case 'k':
55952       if (Subtarget.hasAVX512()) {
55953         if (VT == MVT::i1)
55954           return std::make_pair(0U, &X86::VK1RegClass);
55955         if (VT == MVT::i8)
55956           return std::make_pair(0U, &X86::VK8RegClass);
55957         if (VT == MVT::i16)
55958           return std::make_pair(0U, &X86::VK16RegClass);
55959       }
55960       if (Subtarget.hasBWI()) {
55961         if (VT == MVT::i32)
55962           return std::make_pair(0U, &X86::VK32RegClass);
55963         if (VT == MVT::i64)
55964           return std::make_pair(0U, &X86::VK64RegClass);
55965       }
55966       break;
55967     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
55968       if (Subtarget.is64Bit()) {
55969         if (VT == MVT::i8 || VT == MVT::i1)
55970           return std::make_pair(0U, &X86::GR8RegClass);
55971         if (VT == MVT::i16)
55972           return std::make_pair(0U, &X86::GR16RegClass);
55973         if (VT == MVT::i32 || VT == MVT::f32)
55974           return std::make_pair(0U, &X86::GR32RegClass);
55975         if (VT != MVT::f80 && !VT.isVector())
55976           return std::make_pair(0U, &X86::GR64RegClass);
55977         break;
55978       }
55979       LLVM_FALLTHROUGH;
55980       // 32-bit fallthrough
55981     case 'Q':   // Q_REGS
55982       if (VT == MVT::i8 || VT == MVT::i1)
55983         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
55984       if (VT == MVT::i16)
55985         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
55986       if (VT == MVT::i32 || VT == MVT::f32 ||
55987           (!VT.isVector() && !Subtarget.is64Bit()))
55988         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
55989       if (VT != MVT::f80 && !VT.isVector())
55990         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
55991       break;
55992     case 'r':   // GENERAL_REGS
55993     case 'l':   // INDEX_REGS
55994       if (VT == MVT::i8 || VT == MVT::i1)
55995         return std::make_pair(0U, &X86::GR8RegClass);
55996       if (VT == MVT::i16)
55997         return std::make_pair(0U, &X86::GR16RegClass);
55998       if (VT == MVT::i32 || VT == MVT::f32 ||
55999           (!VT.isVector() && !Subtarget.is64Bit()))
56000         return std::make_pair(0U, &X86::GR32RegClass);
56001       if (VT != MVT::f80 && !VT.isVector())
56002         return std::make_pair(0U, &X86::GR64RegClass);
56003       break;
56004     case 'R':   // LEGACY_REGS
56005       if (VT == MVT::i8 || VT == MVT::i1)
56006         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
56007       if (VT == MVT::i16)
56008         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
56009       if (VT == MVT::i32 || VT == MVT::f32 ||
56010           (!VT.isVector() && !Subtarget.is64Bit()))
56011         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
56012       if (VT != MVT::f80 && !VT.isVector())
56013         return std::make_pair(0U, &X86::GR64_NOREXRegClass);
56014       break;
56015     case 'f':  // FP Stack registers.
56016       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
56017       // value to the correct fpstack register class.
56018       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
56019         return std::make_pair(0U, &X86::RFP32RegClass);
56020       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
56021         return std::make_pair(0U, &X86::RFP64RegClass);
56022       if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
56023         return std::make_pair(0U, &X86::RFP80RegClass);
56024       break;
56025     case 'y':   // MMX_REGS if MMX allowed.
56026       if (!Subtarget.hasMMX()) break;
56027       return std::make_pair(0U, &X86::VR64RegClass);
56028     case 'v':
56029     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
56030       if (!Subtarget.hasSSE1()) break;
56031       bool VConstraint = (Constraint[0] == 'v');
56032 
56033       switch (VT.SimpleTy) {
56034       default: break;
56035       // Scalar SSE types.
56036       case MVT::f16:
56037         if (VConstraint && Subtarget.hasFP16())
56038           return std::make_pair(0U, &X86::FR16XRegClass);
56039         break;
56040       case MVT::f32:
56041       case MVT::i32:
56042         if (VConstraint && Subtarget.hasVLX())
56043           return std::make_pair(0U, &X86::FR32XRegClass);
56044         return std::make_pair(0U, &X86::FR32RegClass);
56045       case MVT::f64:
56046       case MVT::i64:
56047         if (VConstraint && Subtarget.hasVLX())
56048           return std::make_pair(0U, &X86::FR64XRegClass);
56049         return std::make_pair(0U, &X86::FR64RegClass);
56050       case MVT::i128:
56051         if (Subtarget.is64Bit()) {
56052           if (VConstraint && Subtarget.hasVLX())
56053             return std::make_pair(0U, &X86::VR128XRegClass);
56054           return std::make_pair(0U, &X86::VR128RegClass);
56055         }
56056         break;
56057       // Vector types and fp128.
56058       case MVT::v8f16:
56059         if (!Subtarget.hasFP16())
56060           break;
56061         LLVM_FALLTHROUGH;
56062       case MVT::f128:
56063       case MVT::v16i8:
56064       case MVT::v8i16:
56065       case MVT::v4i32:
56066       case MVT::v2i64:
56067       case MVT::v4f32:
56068       case MVT::v2f64:
56069         if (VConstraint && Subtarget.hasVLX())
56070           return std::make_pair(0U, &X86::VR128XRegClass);
56071         return std::make_pair(0U, &X86::VR128RegClass);
56072       // AVX types.
56073       case MVT::v16f16:
56074         if (!Subtarget.hasFP16())
56075           break;
56076         LLVM_FALLTHROUGH;
56077       case MVT::v32i8:
56078       case MVT::v16i16:
56079       case MVT::v8i32:
56080       case MVT::v4i64:
56081       case MVT::v8f32:
56082       case MVT::v4f64:
56083         if (VConstraint && Subtarget.hasVLX())
56084           return std::make_pair(0U, &X86::VR256XRegClass);
56085         if (Subtarget.hasAVX())
56086           return std::make_pair(0U, &X86::VR256RegClass);
56087         break;
56088       case MVT::v32f16:
56089         if (!Subtarget.hasFP16())
56090           break;
56091         LLVM_FALLTHROUGH;
56092       case MVT::v64i8:
56093       case MVT::v32i16:
56094       case MVT::v8f64:
56095       case MVT::v16f32:
56096       case MVT::v16i32:
56097       case MVT::v8i64:
56098         if (!Subtarget.hasAVX512()) break;
56099         if (VConstraint)
56100           return std::make_pair(0U, &X86::VR512RegClass);
56101         return std::make_pair(0U, &X86::VR512_0_15RegClass);
56102       }
56103       break;
56104     }
56105   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
56106     switch (Constraint[1]) {
56107     default:
56108       break;
56109     case 'i':
56110     case 't':
56111     case '2':
56112       return getRegForInlineAsmConstraint(TRI, "x", VT);
56113     case 'm':
56114       if (!Subtarget.hasMMX()) break;
56115       return std::make_pair(0U, &X86::VR64RegClass);
56116     case 'z':
56117       if (!Subtarget.hasSSE1()) break;
56118       switch (VT.SimpleTy) {
56119       default: break;
56120       // Scalar SSE types.
56121       case MVT::f16:
56122         if (!Subtarget.hasFP16())
56123           break;
56124         return std::make_pair(X86::XMM0, &X86::FR16XRegClass);
56125       case MVT::f32:
56126       case MVT::i32:
56127         return std::make_pair(X86::XMM0, &X86::FR32RegClass);
56128       case MVT::f64:
56129       case MVT::i64:
56130         return std::make_pair(X86::XMM0, &X86::FR64RegClass);
56131       case MVT::v8f16:
56132         if (!Subtarget.hasFP16())
56133           break;
56134         LLVM_FALLTHROUGH;
56135       case MVT::f128:
56136       case MVT::v16i8:
56137       case MVT::v8i16:
56138       case MVT::v4i32:
56139       case MVT::v2i64:
56140       case MVT::v4f32:
56141       case MVT::v2f64:
56142         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
56143       // AVX types.
56144       case MVT::v16f16:
56145         if (!Subtarget.hasFP16())
56146           break;
56147         LLVM_FALLTHROUGH;
56148       case MVT::v32i8:
56149       case MVT::v16i16:
56150       case MVT::v8i32:
56151       case MVT::v4i64:
56152       case MVT::v8f32:
56153       case MVT::v4f64:
56154         if (Subtarget.hasAVX())
56155           return std::make_pair(X86::YMM0, &X86::VR256RegClass);
56156         break;
56157       case MVT::v32f16:
56158         if (!Subtarget.hasFP16())
56159           break;
56160         LLVM_FALLTHROUGH;
56161       case MVT::v64i8:
56162       case MVT::v32i16:
56163       case MVT::v8f64:
56164       case MVT::v16f32:
56165       case MVT::v16i32:
56166       case MVT::v8i64:
56167         if (Subtarget.hasAVX512())
56168           return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
56169         break;
56170       }
56171       break;
56172     case 'k':
56173       // This register class doesn't allocate k0 for masked vector operation.
56174       if (Subtarget.hasAVX512()) {
56175         if (VT == MVT::i1)
56176           return std::make_pair(0U, &X86::VK1WMRegClass);
56177         if (VT == MVT::i8)
56178           return std::make_pair(0U, &X86::VK8WMRegClass);
56179         if (VT == MVT::i16)
56180           return std::make_pair(0U, &X86::VK16WMRegClass);
56181       }
56182       if (Subtarget.hasBWI()) {
56183         if (VT == MVT::i32)
56184           return std::make_pair(0U, &X86::VK32WMRegClass);
56185         if (VT == MVT::i64)
56186           return std::make_pair(0U, &X86::VK64WMRegClass);
56187       }
56188       break;
56189     }
56190   }
56191 
56192   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
56193     return std::make_pair(0U, &X86::GR32RegClass);
56194 
56195   // Use the default implementation in TargetLowering to convert the register
56196   // constraint into a member of a register class.
56197   std::pair<Register, const TargetRegisterClass*> Res;
56198   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
56199 
56200   // Not found as a standard register?
56201   if (!Res.second) {
56202     // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
56203     // to/from f80.
56204     if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
56205       // Map st(0) -> st(7) -> ST0
56206       if (Constraint.size() == 7 && Constraint[0] == '{' &&
56207           tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
56208           Constraint[3] == '(' &&
56209           (Constraint[4] >= '0' && Constraint[4] <= '7') &&
56210           Constraint[5] == ')' && Constraint[6] == '}') {
56211         // st(7) is not allocatable and thus not a member of RFP80. Return
56212         // singleton class in cases where we have a reference to it.
56213         if (Constraint[4] == '7')
56214           return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
56215         return std::make_pair(X86::FP0 + Constraint[4] - '0',
56216                               &X86::RFP80RegClass);
56217       }
56218 
56219       // GCC allows "st(0)" to be called just plain "st".
56220       if (StringRef("{st}").equals_insensitive(Constraint))
56221         return std::make_pair(X86::FP0, &X86::RFP80RegClass);
56222     }
56223 
56224     // flags -> EFLAGS
56225     if (StringRef("{flags}").equals_insensitive(Constraint))
56226       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
56227 
56228     // dirflag -> DF
56229     // Only allow for clobber.
56230     if (StringRef("{dirflag}").equals_insensitive(Constraint) &&
56231         VT == MVT::Other)
56232       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
56233 
56234     // fpsr -> FPSW
56235     if (StringRef("{fpsr}").equals_insensitive(Constraint))
56236       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
56237 
56238     return Res;
56239   }
56240 
56241   // Make sure it isn't a register that requires 64-bit mode.
56242   if (!Subtarget.is64Bit() &&
56243       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
56244       TRI->getEncodingValue(Res.first) >= 8) {
56245     // Register requires REX prefix, but we're in 32-bit mode.
56246     return std::make_pair(0, nullptr);
56247   }
56248 
56249   // Make sure it isn't a register that requires AVX512.
56250   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
56251       TRI->getEncodingValue(Res.first) & 0x10) {
56252     // Register requires EVEX prefix.
56253     return std::make_pair(0, nullptr);
56254   }
56255 
56256   // Otherwise, check to see if this is a register class of the wrong value
56257   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
56258   // turn into {ax},{dx}.
56259   // MVT::Other is used to specify clobber names.
56260   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
56261     return Res;   // Correct type already, nothing to do.
56262 
56263   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
56264   // return "eax". This should even work for things like getting 64bit integer
56265   // registers when given an f64 type.
56266   const TargetRegisterClass *Class = Res.second;
56267   // The generic code will match the first register class that contains the
56268   // given register. Thus, based on the ordering of the tablegened file,
56269   // the "plain" GR classes might not come first.
56270   // Therefore, use a helper method.
56271   if (isGRClass(*Class)) {
56272     unsigned Size = VT.getSizeInBits();
56273     if (Size == 1) Size = 8;
56274     Register DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
56275     if (DestReg > 0) {
56276       bool is64Bit = Subtarget.is64Bit();
56277       const TargetRegisterClass *RC =
56278           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
56279         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
56280         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
56281         : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
56282         : nullptr;
56283       if (Size == 64 && !is64Bit) {
56284         // Model GCC's behavior here and select a fixed pair of 32-bit
56285         // registers.
56286         switch (DestReg) {
56287         case X86::RAX:
56288           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
56289         case X86::RDX:
56290           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
56291         case X86::RCX:
56292           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
56293         case X86::RBX:
56294           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
56295         case X86::RSI:
56296           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
56297         case X86::RDI:
56298           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
56299         case X86::RBP:
56300           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
56301         default:
56302           return std::make_pair(0, nullptr);
56303         }
56304       }
56305       if (RC && RC->contains(DestReg))
56306         return std::make_pair(DestReg, RC);
56307       return Res;
56308     }
56309     // No register found/type mismatch.
56310     return std::make_pair(0, nullptr);
56311   } else if (isFRClass(*Class)) {
56312     // Handle references to XMM physical registers that got mapped into the
56313     // wrong class.  This can happen with constraints like {xmm0} where the
56314     // target independent register mapper will just pick the first match it can
56315     // find, ignoring the required type.
56316 
56317     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
56318     if (VT == MVT::f16)
56319       Res.second = &X86::FR16XRegClass;
56320     else if (VT == MVT::f32 || VT == MVT::i32)
56321       Res.second = &X86::FR32XRegClass;
56322     else if (VT == MVT::f64 || VT == MVT::i64)
56323       Res.second = &X86::FR64XRegClass;
56324     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
56325       Res.second = &X86::VR128XRegClass;
56326     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
56327       Res.second = &X86::VR256XRegClass;
56328     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
56329       Res.second = &X86::VR512RegClass;
56330     else {
56331       // Type mismatch and not a clobber: Return an error;
56332       Res.first = 0;
56333       Res.second = nullptr;
56334     }
56335   } else if (isVKClass(*Class)) {
56336     if (VT == MVT::i1)
56337       Res.second = &X86::VK1RegClass;
56338     else if (VT == MVT::i8)
56339       Res.second = &X86::VK8RegClass;
56340     else if (VT == MVT::i16)
56341       Res.second = &X86::VK16RegClass;
56342     else if (VT == MVT::i32)
56343       Res.second = &X86::VK32RegClass;
56344     else if (VT == MVT::i64)
56345       Res.second = &X86::VK64RegClass;
56346     else {
56347       // Type mismatch and not a clobber: Return an error;
56348       Res.first = 0;
56349       Res.second = nullptr;
56350     }
56351   }
56352 
56353   return Res;
56354 }
56355 
56356 InstructionCost X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
56357                                                         const AddrMode &AM,
56358                                                         Type *Ty,
56359                                                         unsigned AS) const {
56360   // Scaling factors are not free at all.
56361   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
56362   // will take 2 allocations in the out of order engine instead of 1
56363   // for plain addressing mode, i.e. inst (reg1).
56364   // E.g.,
56365   // vaddps (%rsi,%rdx), %ymm0, %ymm1
56366   // Requires two allocations (one for the load, one for the computation)
56367   // whereas:
56368   // vaddps (%rsi), %ymm0, %ymm1
56369   // Requires just 1 allocation, i.e., freeing allocations for other operations
56370   // and having less micro operations to execute.
56371   //
56372   // For some X86 architectures, this is even worse because for instance for
56373   // stores, the complex addressing mode forces the instruction to use the
56374   // "load" ports instead of the dedicated "store" port.
56375   // E.g., on Haswell:
56376   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
56377   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
56378   if (isLegalAddressingMode(DL, AM, Ty, AS))
56379     // Scale represents reg2 * scale, thus account for 1
56380     // as soon as we use a second register.
56381     return AM.Scale != 0;
56382   return -1;
56383 }
56384 
56385 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
56386   // Integer division on x86 is expensive. However, when aggressively optimizing
56387   // for code size, we prefer to use a div instruction, as it is usually smaller
56388   // than the alternative sequence.
56389   // The exception to this is vector division. Since x86 doesn't have vector
56390   // integer division, leaving the division as-is is a loss even in terms of
56391   // size, because it will have to be scalarized, while the alternative code
56392   // sequence can be performed in vector form.
56393   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
56394   return OptSize && !VT.isVector();
56395 }
56396 
56397 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
56398   if (!Subtarget.is64Bit())
56399     return;
56400 
56401   // Update IsSplitCSR in X86MachineFunctionInfo.
56402   X86MachineFunctionInfo *AFI =
56403       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
56404   AFI->setIsSplitCSR(true);
56405 }
56406 
56407 void X86TargetLowering::insertCopiesSplitCSR(
56408     MachineBasicBlock *Entry,
56409     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
56410   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
56411   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
56412   if (!IStart)
56413     return;
56414 
56415   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
56416   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
56417   MachineBasicBlock::iterator MBBI = Entry->begin();
56418   for (const MCPhysReg *I = IStart; *I; ++I) {
56419     const TargetRegisterClass *RC = nullptr;
56420     if (X86::GR64RegClass.contains(*I))
56421       RC = &X86::GR64RegClass;
56422     else
56423       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
56424 
56425     Register NewVR = MRI->createVirtualRegister(RC);
56426     // Create copy from CSR to a virtual register.
56427     // FIXME: this currently does not emit CFI pseudo-instructions, it works
56428     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
56429     // nounwind. If we want to generalize this later, we may need to emit
56430     // CFI pseudo-instructions.
56431     assert(
56432         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
56433         "Function should be nounwind in insertCopiesSplitCSR!");
56434     Entry->addLiveIn(*I);
56435     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
56436         .addReg(*I);
56437 
56438     // Insert the copy-back instructions right before the terminator.
56439     for (auto *Exit : Exits)
56440       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
56441               TII->get(TargetOpcode::COPY), *I)
56442           .addReg(NewVR);
56443   }
56444 }
56445 
56446 bool X86TargetLowering::supportSwiftError() const {
56447   return Subtarget.is64Bit();
56448 }
56449 
56450 /// Returns true if stack probing through a function call is requested.
56451 bool X86TargetLowering::hasStackProbeSymbol(MachineFunction &MF) const {
56452   return !getStackProbeSymbolName(MF).empty();
56453 }
56454 
56455 /// Returns true if stack probing through inline assembly is requested.
56456 bool X86TargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
56457 
56458   // No inline stack probe for Windows, they have their own mechanism.
56459   if (Subtarget.isOSWindows() ||
56460       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
56461     return false;
56462 
56463   // If the function specifically requests inline stack probes, emit them.
56464   if (MF.getFunction().hasFnAttribute("probe-stack"))
56465     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
56466            "inline-asm";
56467 
56468   return false;
56469 }
56470 
56471 /// Returns the name of the symbol used to emit stack probes or the empty
56472 /// string if not applicable.
56473 StringRef
56474 X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
56475   // Inline Stack probes disable stack probe call
56476   if (hasInlineStackProbe(MF))
56477     return "";
56478 
56479   // If the function specifically requests stack probes, emit them.
56480   if (MF.getFunction().hasFnAttribute("probe-stack"))
56481     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
56482 
56483   // Generally, if we aren't on Windows, the platform ABI does not include
56484   // support for stack probes, so don't emit them.
56485   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
56486       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
56487     return "";
56488 
56489   // We need a stack probe to conform to the Windows ABI. Choose the right
56490   // symbol.
56491   if (Subtarget.is64Bit())
56492     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
56493   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
56494 }
56495 
56496 unsigned
56497 X86TargetLowering::getStackProbeSize(MachineFunction &MF) const {
56498   // The default stack probe size is 4096 if the function has no stackprobesize
56499   // attribute.
56500   unsigned StackProbeSize = 4096;
56501   const Function &Fn = MF.getFunction();
56502   if (Fn.hasFnAttribute("stack-probe-size"))
56503     Fn.getFnAttribute("stack-probe-size")
56504         .getValueAsString()
56505         .getAsInteger(0, StackProbeSize);
56506   return StackProbeSize;
56507 }
56508 
56509 Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
56510   if (ML->isInnermost() &&
56511       ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
56512     return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
56513   return TargetLowering::getPrefLoopAlignment();
56514 }
56515